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?
public void Print(Son object)
doesn't overridepublic void Print(Father object)
. It overloads it.That said,
DoSmth(Father object)
is executed in both case on aFather
instance, so it would callpublic void Print(Father object)
ofFather
class even ifSon
class did override it.If you change the
Son
class method to:and change your
main
to:You'll get the output