N
N
Nickname1922021-01-13 20:34:31
Java
Nickname192, 2021-01-13 20:34:31

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;}

and method
public int pow() { return a*a; }
} //close
.
There is a child class:
public class B extends A{
public B(int a){
super(a); }

At the entry point, more precisely in the main method
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);
}

Class "B" does not have a field "a" and I read that private fields are not inherited, how can you explain this?

psvm
means public static void main

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2021-01-13
@Nickname192

Class "B" does not have a field "a" and I read that private fields are not inherited, how can you explain this?

This means that B seems to have such a field, but due to the fact that it is private, only parent methods have access to it.
Class B in your case passes a value to the parent's constructor to initialize that field.

E
Erik Mironov, 2021-01-13
@Erik_Mironov

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 question

Ask a Question

731 491 924 answers to any question