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
.
Private Members in a SuperclassA subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
private methods are not inherited. A does not have a public say() method therefore this program should not compile.
In Java private methods are the methods having private access modifier and are restricted to be access in the defining class only and are not visible in their child class due to which are not eligible for overridden. However, we can define a method with the same name in the child class and could access in parent class.
No, we cannot override private or static methods in Java. Private methods in Java are not visible to any other class which limits their scope to the class in which they are declared.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With