Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...