Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

private method in inheritance in Java

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.

like image 342
pei wang Avatar asked Oct 19 '13 02:10

pei wang


People also ask

Is private methods inherited in Java?

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.

Can we access private method in inheritance?

private methods are not inherited. A does not have a public say() method therefore this program should not compile.

What is a private method in Java?

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.

Can we override private method in inheritance?

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.


1 Answers

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.
like image 100
nhgrif Avatar answered Oct 05 '22 13:10

nhgrif