(Java) How to call a overriden "inherited" method from the super class?

120 Views Asked by At

Let's go directly to the code:

Father.java:

public class Father {

    public void DoSmth(Father object) {
        // Do something else and print
        Print(object);
    }

    public void Print(Father object) {
        System.out.println("Father");
    }

}

Son.java:

public class Son extends Father {

    public void Print(Son object) {
        System.out.println("Son");
    }

}

Main.java:

public class Main {

    public static void main(String[] args) {

        Father o1 = new Father();
        Son o2 = new Son();

        o1.DoSmth(o1);
        o1.DoSmth(o2);

    }

}

So, I would like to get:

Father
Son

Howerver, I'm getting:

Father
Father

I really didn't understand very much why (for o1.DoSmth(o2)) it's calling the method from the Father class, since o2 is of type Son. Is there anyway I could get the desired answer?

Thanks in advance

P.S.: I, actually, want to call the method Print (of the Son class) from inside the Father class. Is it possible?

2

There are 2 best solutions below

10
On

public void Print(Son object) doesn't override public void Print(Father object). It overloads it.

That said, DoSmth(Father object) is executed in both case on a Father instance, so it would call public void Print(Father object) of Father class even if Son class did override it.

If you change the Son class method to:

@Override
public void Print(Father object) {
    System.out.println("Son");
}

and change your main to:

public static void main(String[] args) {
    Father o1 = new Father();
    Son o2 = new Son();

    o1.DoSmth(o1);
    o2.DoSmth(o2);
}

You'll get the output

Father
Son
1
On

This is because you are calling the Print method on the Father-instance. If you instead of passing the object as the parameter and called object.Print() you should get your expected result