Karmjit
Karmjit

Reputation: 105

how does base class know about sub class method?

public class BaseClass {
    private String className;

    public BaseClass() {
        className = "[BaseClass]";
    }

    public void executeAB() {
        System.out.println(className + " executingAB()");
        executeA();
        executeB();
    }

    public void executeA() {
        System.out.println(this.className + " executingA()");
    }

    public void executeB() {
        System.out.println(this.className + " executingB()");
    }
}


public class SubClass extends BaseClass {

    private String className;

    public SubClass() {
        this.className = "[SubClass]";
    }

    public void executeA() {
        System.out.println(className + " executingA()");
    }

    public void executeC() {
        System.out.println(className + " executingC()");
    }

    public static void main(String[] args) {

        BaseClass t = new SubClass();
        t.executeAB();
        // t.executeC();
    }
}

In above case , Calling t.executeAB() results in output:

[BaseClass] executingAB()

[SubClass] executingA()

[BaseClass] executingB()

My Question is:

How does BaseClass know about excuteA() method from SubClass, while at the same time t.executeC() call is not possible because BaseClass is not aware of executeC().

Upvotes: 2

Views: 215

Answers (2)

Steve P.
Steve P.

Reputation: 14709

You have a misunderstanding of what you should be doing in inheritance. extends is a reserved word that was wisely chosen. The point of B extending A is to say that B is a subset of A with additional attributes. You're not supposed to redefine x in B; A should be handling x. You should have not className declared in both classes.

As for your example:

 BaseClass t = new SubClass(); 

Calls the constructor for SubClass, which sets className of SubClass to [SubClass]. The super contructor is also called, and className in BaseClass is set to [BaseClass].

 t.executeAB();

Prints the className for BaseClass which is [BaseClass] and then calls:

 executeA(); 
 executeB();

executeA() is a called from SubClass, since t is a SubClass and it's defined, so we get [SubClass] and finally, executeB() is called from BaseClass so again, we get [BaseClass]. As for why you can't call:

t.executeC()

Despite using the constructor for SubClass, t is a BaseClass. According to the principles of OOP, it makes sense that you can't call t.executeC(), since it is not defined for BaseClass.

Upvotes: 2

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44448

You're defining your variable as BaseClass t = new SubClass(); which means you allow space for a different subclass to instantiate. However, in order for this to be possible without breaking existing code, you can only use methods that are defined in the baseclass.

Upvotes: 0

Related Questions