0
Inheritance of private members in Java and C++?
When I create a subclass 'b' from class 'a' in JAVA, and create an instance from 'b', why 'b' does not inherit the private members of 'a'? And what happens if I do it in C++
5 Réponses
+ 3
it inherit the private, but you cannot access it directly
that's what encapsulation is for
0
private - are only seen within a class.
public - everyone
protected - is seen by the class that uses it and children
hope this helps
0
blueelmo answered correctly and oop principles are the same everywhere so the same thing will happen in c++ too.
0
to access the private members of the class use getters and setters
0
You mean:
public class A
{
private int x;
public A(int initX) { x = initX; }
public int getX() { return x; }
public void setX(int num) { x = num; }
};
public class B extends A
{
private int y;
public B(int initX, int initY)
{
super(initX);
y = initY;
}
// not correct:
// public int sumXY()
// { return x + y }
// correct:
public int sumXY()
{return ??????? + y }
};
I do not know what should I write there (???????).
If I had an object, I could call the getX() method like:
A_object.getX().
But I do not know how to call that method.
May be "return getX() + y" ?
Because getX() method was inherited, so I can use.
Is this the solution?