Reputation: 19
so in the code that my teacher gave me, it has the child call a method that returns a value from a private array.
MY question is, what can a child class see from a parent class? Can it see all public methods and variables, and none of the private variables?
class Polygon
{
private int[] sideLengths;
public Polygon(int sides, int ... lengths)
{
int index = 0;
sideLengths = new int[sides];
for (int length: lengths)
{
sideLengths[index] = length;
index += 1;
}
}
public int side(int number)
{
return sideLengths[number];
}
public int perimeter()
{
int total = 0;
for (int index = 0; index < sideLengths.length; index += 1)
{
total += side(index);
}
return total;
}
}
class Rectangle extends Polygon
{
public Rectangle(int sideone, int sidetwo)
{
super(4, sideone, sidetwo, sideone, sidetwo);
}
public int area()
{
return (side(0)*side(1));
}
}
class Square extends Rectangle
{
public Square(int sideone)
{
super(sideone, sideone);
}
}
Upvotes: 1
Views: 206
Reputation: 11
I believe a subclass (child) inherits everything except constructors from the superclass (parent). Even if it's private, in inherits it. You may not be able to access it, but it's there.
That being said, your example demonstrates a private array being accessible by other members of the same class. This is where getters and setters come in. Because the array is private, outside classes can only interact with it should you provide a getter or setter in the same class to do so.
Upvotes: 0