Java Inheritance: method in subclass overrides method in superclass

477 views Asked by At

This is the context: There are 2 classes: Person and Student extends Person

class Person has 1 method: print(Person x) {System.out.println("Person")} (1)

class Student has 2 methods:
print(Student x) {System.out.println("Student")} (2)
and
print(Person x) {System.out.println("Override")} (3)

Then I have:

Person p = new Student();
Student s = new Student();
p.print(s); // prints 'Override' (*)

The explanation i got from the lecture is: Because the declare type is Person, so the compiler will choose the method (1). But the runtime type is Student, so the method (3) overrides it.
My question is: Why did method (2) not override? The argument type here is Student (from the line (*)), should the method (2) have been the overriding one?

Thanks you guys a lot. I appreciate all of your answers

2

There are 2 answers

2
Peter Knall On

The reasons you see "Override" is because "p" is defined as an Object of type "Person" and does not know anything about the additional methods contained in the Student class even though it uses the Student constructor. The reason "Student()" works as an argument for the print method is because Student is a subclass of Person and contains, at least, all the information of a Person object. However, since "p" was defined as a "Student" object, it will use the overridden method of print instead of the one from the Person class. Also, the signatures of the print(Person) and print(Student) are different, so the Student class doesn't see the second print(Student) method as an override.

2
Amit On

polymorphism!. The reason print call routed to Student than Person because print (S) resides within Student and not person. When at Student where the print method was overridden had more broader reference >Print(P) and so print(p) was executed than print(s). you will see this scenarios in Exception handling.