I have a Student class that extends a Person class. I do not have an equals method inside of my super class, just the two in my subclass as shown in the image. I am trying to understand the runtime behavior of my 2nd, 3rd and 4th print statements. Statement 1 calls the equals method that takes a student parameter, which makes sense as both objects being compared are declared type Student. However, statement 2 calls the equals method which takes a person parameter while the last 2 statements call the equals method in the Object class. Can somebody explain why is this so when Java is dynamically typed and the actual runtime object is always a Student. Apologies for any errors in advance! I'm new here and new to Java. I'm not too concerned with the output of each method just which one is being called and why.
public boolean equals(Student s) {
System.out.println("inside student equals");
return true;
}
public boolean equals(Person p) {
System.out.println("inside person equals");
return false;
}
public static void main(String[] args) {
Student s1 = new Student("John", "1", 10, 1.0, 10);
Student s2 = new Student("John", "1", 10, 1.0, 10);
Person s3 = new Student("John", "1", 10, 1.0, 10);
Person s4 = new Student("John", "1", 10, 1.0, 10);
System.out.println(s1.equals(s2)); // 1
System.out.println(s1.equals(s3)); // 2
System.out.println(s3.equals(s4)); // 3
System.out.println(s3.equals(s1)); // 4
}
Output:
inside student equals
true
inside person equals
false
false
false