So I have the following two cases:
Case 1:
public class Person {
private String name = "Person";
private String getName() {
return name;
}
public void printName() {
System.out.println( getName() );
}
}
public class Student extends Person {
private double gpa = 0;
private String getName() {
return “Student”;
}
}
public class Driver {
public static void main(String[] args){
Person p = new Person();
Student s = new Student();
p.printName(); // “Person”
s.printName(); // “Person”
}
}
Case 2:
public class Person {
private String name = "Person";
public String getName() {
return name;
}
public void printName() {
System.out.println( getName() );
}
}
public class Student extends Person {
private double gpa = 0;
public String getName() {
return “Student”;
}
}
public class Driver {
public static void main(String[] args){
Person p = new Person();
Student s = new Student();
p.printName(); // “Person”
s.printName(); // “Student”
}
}
Case 2 makes the most sense (it's intended behavior).
But why does Case 1 not output the same as Case 2 ("Person" instead of "Student")?
From what I understand, non-static calls implicitly use this
. And from this SO post, this
and super
don't "stick". Thus, for the first case, getName()
should use Student
's implementation as this
refers to the Student
instance (regardless of access modifiers). But that doesn't appear to be the case..
Thanks in advance!