SUPER class should get function and attribute from its SUBCLASS. is it possible in Java?
A
a1 a2 a3*
In this example A is SUPER class and it has a1,a2 as subclasses.
Suppose a3 i开发者_高级运维s added to A, then I would like A to get a feature from a3 (it should be optional). This extra feature of a3 should go to A(super class) and also all other children(a1,a2) should get this feature.
Is it possible in Java or Java-design?
No. This is not supported by Java. Note that
class A1 extends A
should not be interpreted as "I'm adding stuff to A". It should be interpreted as "Here's a new class, and as a basis for this class, I'll use A
".
If you have some aspects of a1
, a2
and a3
that should be accessible to A
and thus a1
, a2
and a3
I suggest you do something like
class A {
protected A1 a1 = new A1();
protected A2 a2 = new A2();
protected A3 a3 = new A3();
...
}
You could also make A1
, A2
and A3
non-static inner classes for them to have a reference to instance of the encapsulating A
.
No superclass can not have functionality of sub-class only reverse is possible.
In your case a3 can have all methods defined in A but any newly defined methods in a3 that are not in A is not automatically added to A. If you want to use new functionality in all subclasses then why not directly add it in Super class. So add new functionality in A then access that in a1, a2, and a3.
Parents don't know about children. Functionality flows down the hierarchy tree, not up.
Maybe you should use composition instead of inheritance? When the design is correct you should not expect such a problem. Perhaps the strategy pattern is appropriate in this situation.
No, inheritance in general does not support this behavior, in Java or elsewhere. And that's a good thing.
When you have a class extend another, you're expressing an IS-A relationship. One class is a kind of another. A lion is an animal. A coupe is a car. That sort of thing.
Presume that a human is-a person, and a Martian is-a person. Now, let's say we add another class, a Kryptonian, who is also a person. The addition of the Kryptonian does not suddenly grant you X-ray vision. Sorry.
Check the visitor pattern - it is used for that kind of problems!
Reading your question, it sounds like you come from a C++ background and you've been using multiple inheritance before.
Abstract superclass A has an abstract (virtual) function f().
Abstract subclass a1 inherits from A and has a function f1() which calls f(), but no implementation of f().
Sublass a2 inherits from A and implements f().
Subclass aa1 inhertits from a1 AND a2, causing aa1 to become non-abstract and and aa1.f1() will call a2.f().
This is not possible in Java. There is no multiple inheritance. Look at composition or some form of strategy pattern.
On a side-note: multiple inheritance was always a good-awful pattern and was a surefire way to make any code completely impossible to understand. Thank god they did away with it.
精彩评论