Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Call a base super class method while skipping intermediate inherited super classes [duplicate]

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?

like image 721
eBehbahani Avatar asked Nov 17 '14 18:11

eBehbahani


People also ask

What are the conditions for using super () method?

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.

How does super () method play an important role in inheritance in java?

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.

Can you use Super twice java?

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.

How can we protect sub class to override the method of super class explain with example?

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 .


1 Answers

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

like image 150
Virmundi Avatar answered Oct 11 '22 11:10

Virmundi