Answer the question
In order to leave comments, you need to log in
Inheritance of private fields and methods?
Hello, I have a question: there is a class A, it has a private int a; and constructor
public class A{ //open
private int a;
public A(int a){ this.a = a;}
public int pow() { return a*a; }
} //close
. public class B extends A{
public B(int a){
super(a); }
psvm(String []args){
A a = new A(5);
B b = new B(6);
int aPow = a.pow();
int bPow = b.pow();
sout("aPow = " + aPow + " bPow = " + bPow);
}
psvmmeans public static void main
Answer the question
In order to leave comments, you need to log in
Class "B" does not have a field "a" and I read that private fields are not inherited, how can you explain this?
A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods to access its private fields, these can also be used by the subclass. Also, if the child class is a nested class of the parent class, then it has access to all private fields and methods of the parent class. In your case, you must call the constructor of the parent class in the child class. This does not mean that you have access to a private field of the parent class.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question