简体   繁体   中英

Access to Private Members of a Superclass

What is the example of indirect access to private member of superclass from subclass?

A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.

Quote from http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

In the quote, we talk about "nested" class

here is an example of how an inner class can access private fields of the outer class.

class OuterClass {
private int x = 7;

public void makeInner(){
    InnerClass in = new InnerClass();
    in.seeOuter();
}
class InnerClass {
    public void seeOuter() {
        System.out.println("Outer x is " + x);
    }
}
public static void main(String[] args) {
    OuterClass.InnerClass inner = new OuterClass().new InnerClass();
    inner.seeOuter();
}

}

Finally, if you extend a class with the InnerClass, they will also access the private fields of the OuterClass if your InnerClass is public or protected

It is to be supposed (but the compiler does not enforce it, only warns), that a private method will end being used by a public , protected or default method (otherwise it is useless).

So, the extending class can "indirectly" call the private method by calling the public , protected or default method that ends calling the private method.

Yes, we can access private members of a superclass in the child class through the public method of the superclass which can be invoked from the child class's reference variable heaving the reference id of child class. for example:-

class Base
{
    private int x=10;

    void show()
    {
        System.out.println(x);
    }
}

class Child extends Base
{

    public static void main(String... s)// public static void main(String[] args)
    {    
        //rom jdk 1.7 main can be defined like above
        Child c=new Child();
        c.show();
    }
}

The output will be 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM