Inheritance
public class Rectangle{ // Center coordinate private double x; ❶ private double y; public void move (double dx, double dy){ ❷ x += dx; y += dy; } private double width, height; ❸ ... } |
public class Circle { // Center coordinate private double x; ❶ private double y; public void move (double dx, double dy){ ❷ x += dx; y += dy; } private double radius; ❸ ... } |
-
Create a parent class
Shape
containing common code portions. -
Relate both
Rectangle
andCircle
toShape
.
Common
Rectangle and Circle
attributes:
|
||
---|---|---|
|
||
Rectangle
attributes
|
Circle
attributes
|
|
|
|
-
Derived classes inherit state and behaviour.
-
Refinement, specialization.
-
“is-A” relationship:
-
A rectangle is a shape.
-
A circle is a shape.
-
|
|||
|
|
final double x = 2, y = 3;
final Shape shape = new Shape(x, y);
final double width = 2, height = 5;
final Rectangle r = new Rectangle(x, y , width, height);
final double radius = 2.5;
final Circle circle = new Circle(x, y , radius);
/**
* Creating a shape located at center coordinate.
* @param x The center's x component.
* @param y The center's y component.
*/
public Shape(double x,double y) {
this.x = x;
this.y = y;
}
/**
* Creating a rectangle at (x|y) of given width and height.
* @param x Center's x component.
* @param y Center's y component.
* @param width Rectangle's width.
* @param height Rectangle's height.
*/
public Rectangle(double x, double y,
double width, double height) {
super(x, y) ❶;
this.width = width; this.height = height ❷;
}