Центр дистанционного обучения
Полиморфизм – зачем?
Circle c1 = new Circle(0, 0, 2); Rectangle r1 = new Rectangle(0, 0, 2, 1); Shape[] shapes = {c1, r1};
for (Shape s : shapes) { System.out.println(s.getX());
}
Методы класса Shape наследуются в потомках
online.mirea.ru
Центр дистанционного обучения
Полиморфизм – как?
public class Shape {
private double x; private double y;
public Shape(double x, double y) { this.x = x;
this.y = y;
}
public double getX() { return x;
}
public double getY() { return y;
}
}
online.mirea.ru
Центр дистанционного обучения
Полиморфизм – как?
public class Circle extends Shape {
private double radius;
public Circle(double x, double y, double radius) { super(x, y); // Вызов конструктора базового класса this.radius = radius;
}
public double getRadius() { return radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
online.mirea.ru
Центр дистанционного обучения
Полиморфизм – как?
public class Rectangle extends Shape {
private double width; private double height;
public Rectangle(double x, double y, double width, double height) { super(x, y);
this.width = width; this.height = height;
}
public double getWidth() { return width;
}
public double getHeight() { return height;
}
public double getArea() { return width * height;
}
}
online.mirea.ru
Центр дистанционного обучения
Полиморфизм – как?
Circle c1 = new Circle(0, 0, 2);
Shape s1 = c1;
|
|
x: 0 |
c1 |
|
|
|
|
y: 0 |
|
|
|
|
|
|
radius: 2
s1
s1 и c1 указывают на один и тот же объект, но s1 “видит” только поля x и y
online.mirea.ru