I have confusion about using private methods in inheritance, for example:
public class A {
private void say(int number){
System.out.print("A:"+number);
}
}
public class B extends A{
public void say(int number){
System.out.print("Over:"+number);
}
}
public class Tester {
public static void main(String[] args) {
A a=new B();
a.say(12);
}
}
Based on the codes above, I am confused about the inheritance of private method, is the private method inherited from class A
to B
? Or the say methods in both classes are totally unrelated? As the code has error when it is running in main() method, it seems like class B
cannot invoke the private method from class A
.
If you want a subclass to have access to a superclass method that needs to remain private
, then protected
is the keyword you're looking for.
Private
allows only the class containing the member to access that
member.
Protected
allows the member to be accessed within the class and
all of it's subclasses.
Public
allows anyone to access the member.
The reason you are getting the error is because say(int)
is private. This has nothing to do with inheritance. You can only call a private member method in its definition class.
To answer your inheritance question, B.say()
is a different method - it isn't even overriding method A.say()
because derived classes can't inherit private methods from its base class. Only protected
and public
methods/variables can be inherited and/or overridden.
Private means you can Only access it in that class an no where else.
Subclasses can only invoke or override protected
or public
methods (or methods without access modifiers, if the superclass is in the same package) from their superclasses. private
methods stay in the class in which they're declared and aren't visible to any other class, no matter how it's related.
There are two things going on here.
First, keep in mind the distinction between the type of the reference and the type of the object.
When you say
A a = new B();
the reference is a
of type A
, but the object is of type B
. So when you call a.say(12);
, you are looking at B
from the A
API/interface/perspective.
Second, because you are looking at B
from the A
perspective, you are going to get an error because A
has no public method called say()
. Of course B
does, but remember you are treating B
as an A
. When you do that, you lose any ability (unless you cast later, but don't worry about that for now) to reference those B
methods that A
doesn't know about.
In the end, B
actually never inherits say()
from A
since it can't see it in the first place, and A
has no public method say()
for anyone to access.
Now if you want to really have some fun, make say()
protected in A
and private in B
and see what happens.