I have a question about the following code and its output:
public class MoarTests {
public static void main(String[] args) throws Exception {
Person p = new Student();
Student s = new Student();
p.m(0); // Prints "Person method"
p.m(0.0); // Prints "Person method"
s.m(0); // Prints "Student method"
s.m(0.0); // Prints "Person method"
}
}
class Person {
public void m(double n) {
System.out.println("Person method");
}
}
class Student extends Person {
public void m(int n) {
System.out.println("Student method");
}
}
The most confusing cases for me are p.m(0)
and s.m(0.0)
. In p.m(0)
the method chosen is m(double n)
even though the argument given was an integer, while in s.m(0.0)
it matched the method to m(double n)
even though there is a method in the Student class that can work the the given double arguement.
How does the type of the variable change which method is called? And how are the methods chosen?
A.m(0)
chooses between the methods in the class Person
as A
is the type of Person
(even though the actual object is of type Student
, it is declared as a type Person, so that is used). Because the type of A
(Person
) does not have visibility into the child class methods, this is the only choice available which is the method with the double
argument.
If there were an int method and a double method, the JVM would have chosen the int
method. Actually this is exactly what happens when you call B.m(0). In this case, the JVM has two methods m(int)
and m(double
) and it chooses m(int)
.
B.m(0.0)
does not match with int as 0.0
is double
and not an int