This is a question in-regards to basic inheritance in Java with two classes.
We have two classes, with the first one being a Rectangle
:
private double length;
private double width;
public Rectangle(double length, double width)
{
this.length = length;
this.width = width;
}
Next we have an extension class called Square
, which extends Rectangle
, so through super()
we know that it uses the constructor of the Rectangle
class.
private double side;
public Square(double side)
{
super(side, side);
this.side = side;
}
public void print()
{
System.out.println("I am a square of side " + side);
}
This is our main:
Square b = new Square(6.0);
Rectangle c = (Rectangle) b;
c.print();
We create a object of the type Square
, which would contain two side
variables the double
6.0
Next, we cast b
to Rectangle
c
, which is where my question comes in.
Why would c.print()
print out I am a square of side 6.0
?