pleople.
Please help me understanding the following:
I have 3 scenarios:
1.
public class Test {
public static void main(String[] args) {
new Person().printPerson();
new Student().printPerson();
}
}
class Student extends Person {
public String getInfo() {
return "Student";
}
}
class Person {
public String getInfo() {
return "Person";
}
public void printPerson() {
System.out.println(getInfo());
}
}
That returns:
Person
Student
2.
public class Test {
public static void main(String[] args) {
new Person().printPerson();
new Student().printPerson();
}
}
class Student extends Person {
private String getInfo() {
return "Student";
}
}
class Person {
private String getInfo() {
return "Person";
}
public void printPerson() {
System.out.println(getInfo());
}
}
That returns:
Person
Person
3.
public class Test {
public static void main(String[] args) {
new Person().printPerson();
new Student().printPerson();
}
}
class Student extends Person {
public String getInfo() {
return "Student";
}
}
class Person {
private String getInfo() {
return "Person";
}
public void printPerson() {
System.out.println(getInfo());
}
}
That also returns:
Person
Person
The first "Person" result is OK in every case, my problem comes with the second call.
Scenario 1: I thought that that was happening because 'Student' was inheriting 'printPerson' from 'Person' so 'Student' is calling its inherited 'printPerson' and this is calling its own 'getInfo' and thats it.
Scenario 2: Thinking in Scenario 1 well, 'Student' still can inherit 'printPerson' because is public and it should be able to call its own 'getInfo' but, evidently that is not what happens because it is showing "Person" instead of "Student".
We can think this is happening because is not "Inheritance" what is working here but "Dynamic Binding" and it is using the 'printPerson' from 'Person' and, because the 'getInfo' in Student is private is not accesible so it will use the 'getInfo' in 'Person'.
The thing is that, if the second statement is true, why it didn't do the same thing in Scenario 1?
Scenario 3: worst of the worst, the 'getInfo' in 'Student' is public, it should be accesible but it is still printing "Person".
Please help me understanding why it is happening what it is happening in each scenario.
Thanks a lot!
Edit: I just read the other question that they say is the same as mine... There they are asking about private and override... I understand that a private method cannot be overwriten simply because the subclass trying to overwrite it cannot access it, so it cannot be overwriten...
My questiong here is how the methods are called? Whay in one scenario the method called is from 'Student' and in the other scenarios is from 'Person'?
I hope this clarifies my doubt. Thanks!!