Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force use of a base class method in Java

Lets say I have two classes Base and Derived:

public class Base {
    public Base() { }
    public void methodA() {
        System.out.println("Base: methodA");
        methodB();
    }
    public void methodB() {
        System.out.println("Base: methodB");
    }
}
public class Derived extends Base {
    public Derived() { }
    public void methodA() {
        super.methodA();
        System.out.println("Derived: methodA");
    }
    public void methodB() {
        System.out.println("Derived: methodB");
    }
}

Now with this:

Base d = new Derived();
d.methodA();

Will print:

Base: methodA
Derived: methodB
Derived: methodA

My question is: Is it possible to force d.methodA() to use Base.methodB()? I want the code to print out:

Base: methodA
Base: methodB
Derived: methodA

For those knowledgable in C++, this could be done with something like Base::methodB() in the Base class. Is there an equivalent in Java?

I am almost sure this has been asked before, but I was unable to find anything, I'm sorry if this is a duplicate.

like image 364
yizzlez Avatar asked May 06 '14 01:05

yizzlez


People also ask

What is use of base class in Java?

A base class is a class, in an object-oriented programming language, from which other classes are derived. It facilitates the creation of other classes that can reuse the code implicitly inherited from the base class (except constructors and destructors).

How do you call a method of base class in derived class in Java?

Base baseRef = new derived(); // Due to dynamic binding, will call the derived class // display() function baseRef. display(); Base baseRef = new derived(); // Due to dynamic binding, will call the derived class // display() function baseRef. display();

How many base classs are there in Java?

Hierarchical Inheritance In Java A class can have more than one class derived from it. So we have one base or superclass and more than one subclasses. This type of inheritance is called “Hierarchical inheritance”.


1 Answers

If a method in the base class can have an override, and the derived class has provided one, there is no way to force a call to the method of the base class.

If the base class needs to call the functionality in the base class, it can put it into a separate method, and declare it final. Then it could make a decision between its own implementation and the derived implementation like this:

public class Base {
    public Base() { }
    public void methodA() {
        System.out.println("Base: methodA");
        // Call the derived method
        methodB();
        // Call the base method
        methodB_impl();
    }
    public final void methodB_impl() {
        System.out.println("Base: methodB");
    }
    public void methodB() {
        methodB_impl();
    }
}
like image 174
Sergey Kalinichenko Avatar answered Sep 29 '22 01:09

Sergey Kalinichenko