Basically, can you do something like this?
class Base {
private void foo(){
println("Base");
}
}
class Derived extends Base {
public void foo(){
println("Derived");
}
}
Basically, can you do something like this?
class Base {
private void foo(){
println("Base");
}
}
class Derived extends Base {
public void foo(){
println("Derived");
}
}
In your example, the derived class is not less restrictive. The methods in the base and derived class have nothing to do with each other. The method Derived.foo()
does not override Base.foo()
. Consequently, the private access of Base.foo()
is not made less restrictive by Derived.foo()
.
This is covered in the Java Language Specification, Section 8.4.8, Inheritance, Overriding, and Hiding.
8.4.8.1 Overriding (by Instance Methods)
An instance method mC declared in or inherited by class C, overrides from C another method mA declared in class A, iff all of the following are true:
- A is a superclass of C.
- C does not inherit mA.
- The signature of mC is a subsignature (§8.4.2) of the signature of mA.
- One of the following is true:
- mA is public.
- mA is protected.
- mA is declared with package access in the same package as C, and either C declares mC or mA is a member of the direct superclass of C.
- mA is declared with package access and mC overrides mA from some superclass of C.
- mA is declared with package access and mC overrides a method m' from C (m' distinct from mC and mA), such that m' overrides mA from some superclass of C
In short, private methods cannot be overridden by a subclass. If you call the private method from the base class, it will call that private method, not a method of the same name and signature in a subclass.
Compiler wont give you a error but its not overriding the super class method. To be able to override child class has to be able to see the method first, but since it is private its just not visible to the child class, so it is considered as a method in the child class instead