The Shape
Hierarchy
public interface Shape
{
public double area();
public double diameter();
public double perimeter();
}
Here we are inking the contract offered by the
interface Shape
.
public class Rectangle implements Shape
{
private double width;
private double height;
public Rectangle(double width, double height)
{
this.width = width;
this.height = height;
}
public double area()
{
return width*height;
}
public double diameter()
{
return Math.hypot(width, height);
}
public double perimeter()
{
return 2*(width + height);
}
}
This is no surprise.
jshell> /open Shape.java
jshell> /open Rectangle.java
jshell> Rectangle r = new Rectangle(6,8);
r ==> Rectangle@1d56ce6a
jshell> r.diameter()
$4 ==> 10.0
jshell> r.perimeter()
$5 ==> 28.0
jshell> r.area()
$6 ==> 48.0
Since a Shape
is a supertype of
Rectangle
, a variable of Shape
type can point at an object of type Rectangle
.
jshell> Shape s = new Rectangle(3,4);
s ==> Rectangle@238e0d81
jshell> s.area()
$8 ==> 12.0
The Object
type is the root type of the
Java object type system. Anything of object type is a subtype
of Object
. Here we see an Object
pointing at a Rectangle
!
jshell> Object o = new Rectangle(6,8);
o ==> Rectangle@728938a9
jshell> o
o ==> Rectangle@728938a9
Uh oh. Look at this.
jshell> o.area()
| Error:
| cannot find symbol
| symbol: method area()
| o.area()
| ^----^
Visibility Principle The type of a variable
dictates what methods are visible. An Object
variable
can only see Object
methods. A Shape
variable is required to be able to see area
,
diameter
, and perimeter
.
We now exit jshell
.
jshell> /exit
| Goodbye
Now let's add a toString
method to our Rectangle
@Override
public String toString()
{
return String.format("Rectangle(%s, %s)", width, height);
}
We open a fresh jshell
and do this.
jshell> /open Shape.java
jshell> /open Rectangle.java
jshell> Object o = new Rectangle(3,4);
o ==> Rectangle(3.0, 4.0)
jshell> o.toString()
$4 ==> "Rectangle(3.0, 4.0)"
jshell> /exit
| Goodbye
Delegation Prinicple Method calls are delegated to the
object that is pointed at. Notice we have an Object
variable pointing at a Rectangle
, but the Rectangle
's
toString()
method was called.