Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when using super().method, which methods is called in this situation

Tags:

java

Suppose you have an object of type BlahChild that is an extension of BlahParent, what happens when BlahChild calls super().someMethod and someMethod contains a call to another function, anotherMethod() that is also overriden in BlahChild?

Does BlahChild's anotherMethod get called, or BlahParent's anotherMethod?

like image 877
BobTurbo Avatar asked Dec 23 '22 01:12

BobTurbo


1 Answers

Non-static methods are always virtual in java, so yes.

From wikipedia:

In Java, all non-static methods are by default "virtual functions." Only methods marked with the keyword final, which cannot be overridden, along with private methods, which are not inherited, are non-virtual.

It will call the BlahChilds implementation.

Example:

class Parent {
    public void method() {
        System.out.println("Parent: method");
    someOtherMethod();
    }
    public void someOtherMethod() {
        System.out.println("Parent: some other");
    }
}


class Child extends Parent {

    @Override
    public void method() {
        System.out.println("Child: method");
        super.method();
    }

    @Override
    public void someOtherMethod() {
        System.out.println("Child: some other");
    }
}

public class Test {
    public static void main(String[] args) {
        new Child().method();
    }
}

Output:

Child: method
Parent: method
Child: some other   // <-- Child.someOtherMethod gets called, from Parent.method
like image 159
aioobe Avatar answered Dec 28 '22 11:12

aioobe