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!
A static nested class can inherit: an ordinary class. a static nested class that is declared in an outer class or its ancestors.
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.
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.
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.
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
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