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());
}
}
The output to this is:
Person
Person
Why is the second line not Student? The parent getInfo()
is private but does that mean that the second call of printPerson()
is prevented from finding the child getInfo()
(which is public)? I think that the child method cannot inherit the private getInfo()
so overriding does not occur.
The parent getInfo() is private but does that mean that the second call of printPerson() is prevented from finding the child getInfo() (which is public)?
Yes. The subclass's getInfo()
method is not overriding the superclass's one, as it doesn't even logically know about it. Private methods can't be overridden.
From section 8.4.8.1 of the JLS:
An instance method m1, declared in class C, overrides another instance method m2, declared in class A iff all of the following are true:
- C is a subclass of A.
- The signature of m1 is a subsignature (ยง8.4.2) of the signature of m2.
- Either:
- m2 is public, protected, or declared with default access in the same package as C, or
- m1 overrides a method m3 (m3 distinct from m1, m3 distinct from m2), such that m3 overrides m2.
Note the first sub-bullet - in your case, m2
is Person.getInfo
, and that isn't public, protected or declared with default access in the same package - so that sub-bullet doesn't apply. The other sub-bullet doesn't apply either, so you're not meeting all the requirements for overriding.
You should use the @Override
annotation when you're trying to override a method in a superclass - that way if you're doing something wrong, you'll get a compile-time error instead of just getting unexpected behaviour at execution time.
See more on this question at Stackoverflow