Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java override method invocation

I have a super class:

public class SuperClass {

    public void dosomething() {
        firstMethod();
        secondMethod();
    }

    public void firstMethod() {
        System.out.println("Super first method");
    }

    public void secondMethod() {
        System.out.println("Super second method");
    }
}

A sub class:

public class SubClass extends SuperClass {

    public void dosomething() {
        super.dosomething();
    }

    public void firstMethod() {
        System.out.println("Sub first method");
    }

    public void secondMethod() {
        System.out.println("Sub second method");
    }
}

A test class:

public static void main(String[] args) {
      SubClass sub = new SubClass();
      sub.dosomething();
      SuperClass sup = new SuperClass();
      sup.dosomething()
}

when I run the test method, I got this:

Sub first method
Sub second method

Can you tell me how this happened? In the sub class dosomething method, I called super.dosomething() and I think the super method will be called, but the override method in sub class was called.

if I do this:
SuperClass superClass = new SuperClass();
superClass.dosomething();


the result is:
Super first method
Super second method

The difference is method invocation place. I think there must be something I don`t know ):

oops!the super reference pointed to subclass in the first example...

like this:

SuperClass sub = new SubClass();
sub.firstMethod();
sub.secondMethod();

like image 388
Felix Avatar asked Jun 08 '26 12:06

Felix


2 Answers

In java, the methods binding is always dynamic [ignoring static and private methods here]. Thus, when you override firstMethod() and secondMethod(), any time an object of type SubClass will try to invoke one of them - the overriden method will be invoked - even if it [the invokation] is from the parent's method.

So, as expected - when you invoke super.doSomething(), it calls firstMethod() and secondMethod(), and the overriden methods are being called.

like image 117
amit Avatar answered Jun 11 '26 02:06

amit


Your object on which the methods are invoked is of type SubClass, not SuperClass. Even if you call a method that is only defined in SuperClass, your execution context remains SubClass. So any method that is invoked that is overridden will in fact execute the overridden method.

The thing to take away from this is that by declaring firstMethod and secondMethod as public, SuperClass is in fact allowing subclasses to override their behaviour. If this is not appropriate, the methods should be private, or final.

like image 44
Joeri Hendrickx Avatar answered Jun 11 '26 04:06

Joeri Hendrickx