I have confusion about using private methods in inheritance, for example:
public class A {
private void say(int number){
System.out.print(\"A:\"+
Private methods are inherited in sub class ,which means private methods are available in child class but they are not accessible from child class,because here we have to remember the concept of availability and accessibility.
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.
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.
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.