Let say I have three classes:
class A
{
public void method()
{ /* Code specific to A */ }
}
class B extends A
{
@Override
public void method()
{
/*Code specific to B*/
super.method();
}
}
class C extends B
{
@Override
public void method()
{ /* I want to use the code specific to A without using B */ }
}
The goal in this case is to use the code from A without using the code from B. I thought there was a way to do it by calling the super method, but this brings in the code from B as well.
Is there a way to do this?
We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields. In the above example, Animal and Dog both classes have a common property color. If we print color property, it will print the color of current class by default.
The super keyword refers to superclass (parent) objects. It is used to call superclass methods, and to access the superclass constructor. The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.
We can use super() as well this() only once inside constructor. If we use super() twice or this() twice or super() followed by this() or this() followed by super(), then immediately we get compile time error i.e, we can use either super() or this() as first statement inside constructor and not both.
We can only use those access specifiers in subclasses that provide larger access than the access specifier of the superclass. For example, Suppose, a method myClass() in the superclass is declared protected . Then, the same method myClass() in the subclass can be either public or protected , but not private .
The short answer is no. What you're seeing is that your design is flawed. It indicates that you need too move the code in class A out into a helper class. B and C would then use it via composition. You could try using partials to get the behavior you want. See this link for more details. Partial function application in Java 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With