I read the tutorial stuff about abstract classes and am a little unclear on something..
I have an abstract class
abstract class Master implements ActionListener {
static Point p;
static JFrame glass;
/* code to define glass and a mouseListener to it.
The mouselistener essentially registers the mouseclick
and point P where it happened */
}
And the I extend some others
class FirstMaster extends Master {
/* some definitions and stuff */
}
class SecondMaster extends Master {
/* some definitions and stuff */
}
My questions
Sorry for the newbie question but I didnt see an example to figure it out definitively.
EDIT: Since there is a lot of info below I thought I would summarize my understanding of the answers for the benefit of subsequent readers (and please correct if I am mistaken)
Thanks to all.
Question 1: When you declare a static
member object (field) in a top-level class, there is only one of that object in the entire program, period. If the object is x
and it's in class Class1
, Class1.x
will refer to that object. If you have a subclass Class2
that extends Class1
, Class2.x
is another way to refer to the same object, if x
isn't hidden by another declaration of some other x
. But a new static object is not created for the subclass. None of this depends on whether the classes are abstract or not.
Question 2: Any methods declared in ActionListener
need to be implemented, by writing bodies for the methods. You can implement them in Master
or not. Whatever methods you don't implement in Master
, you need to implement in both FirstMaster
and SecondMaster
. If you implement them in Master
, you could still write overriding methods in FirstMaster
or SecondMaster
, but if you don't, they'll inherit the methods you wrote in Master
. I'm not sure what you mean by "each instance" having to define the associated method; you do have to define it in each (non-abstract) subclass.
Question 3: Getting rid of extends
would create a completely different program. The way you've written it, if you have a method that needs an ActionListener
:
public void addListener(ActionListener listener);
you can pass it an instance of a FirstMaster
or a SecondMaster
, since instances of those classes are also indirectly instances of ActionListener
. If you get rid of extends Master
, you can't do that. Even if you get rid of extends Master
and add implements ActionListener
, you could no longer write a method like
public void addMasterListener(Master m);
In order to write a method like this and have it work, you need to be able to pass it instances of FirstMaster
or SecondMaster
. So (as Thomas Uhrig commented), using the extends
is a way to improve your program by using polymorphism, not just a way to avoid code duplication.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments