Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting Nested classes into Subclass

When I was going through this article, under the section Private Members in a Superclass, i saw this line

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.

My question is how can we DIRECTLY access the Nested class of Base in Derived (like we can access any public, protected fields)?

and

if there is a way, how can Derived access p which is private field of Base through Nested?

public class Base {

    protected int f;
    private int p;

    public class Nested {

        public int getP() {
            return p;
        }
    }
}

class Derived extends Base {

    public void newMethod() {
        System.out.println(f); // i understand inheriting protected field

        // how to access the inherited Nested class here? and if accessed how to retrieve 'p' ?
    }

}

Thanks in advance for your time and effort in this thread!

like image 617
sanbhat Avatar asked Jul 17 '13 18:07

sanbhat


People also ask

Can nested classes be inherited?

A static nested class can inherit: an ordinary class. a static nested class that is declared in an outer class or its ancestors.

Can we inherit nested class in Java?

The same Java inheritance rules apply to nested classes. Nested classes which are declared private are not inherited. Nested classes with the default (package) access modifier are only accessible to subclasses if the subclass is located in the same package as the superclass.

Is a nested class a subclass?

In object-oriented programming (OOP), an inner class or nested class is a class declared entirely within the body of another class or interface. It is distinguished from a subclass.

What Cannot be inherited by a subclass?

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.


1 Answers

Base.Nested theClassBro= new Base.Nested();

Or for the Derived class, this should work:

Derived.Nested theClassBro= new Derived.Nested();

I'm not sure if you need to use the super keyword or not

like image 122
But I'm Not A Wrapper Class Avatar answered Sep 28 '22 14:09

But I'm Not A Wrapper Class