灵活调用
替换扩充性强
继承、引用,重写
写一个shap类,有一个方法getArea(),获取图形面积
public class Shap {
/**
*写一个方法获取图形面积
*/
public void getArea(){
System.out.println("面积");
}
}
写一个cycle,写一个rectangle,继承shap
写好私有属性,重写getArea()方法求面积
public class Cycle extends Shap {
private double r;
public Cycle() {
}
public Cycle(double r) {
this.r = r;
}
@Override
public void getArea() {
System.out.println("圆的面积:" + 3.14 * r * r);
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
}
rectangle
私有化长乘宽,无参,有参构造器,方法重写
public class Rectangle extends Shap {
private double length;
private double wide;
public Rectangle() {
}
public Rectangle(double length, double wide) {
this.length = length;
this.wide = wide;
}
@Override
public void getArea() {
System.out.println("矩形的面积:" + length * wide);
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWide() {
return wide;
}
public void setWide(double wide) {
this.wide = wide;
}
}
写一个测试类ShapDemo,类里面有个getShapArea(Shap shap)用于获取任意图形面积。
打印一个圆和一个矩形对象面积
搞两个对象,写方法,注意static。
public class ShapDemo {
public static void main(String[] args) {
Shap shap = new Cycle(10);
getShapDemo(shap);
shap = new Rectangle(10.0, 20.0);
getShapDemo(shap);
}
public static void getShapDemo(Shap shap) {
shap.getArea();
}
}
标签:wide,shap,double,void,多态,length,public
From: https://www.cnblogs.com/seeingxi/p/16748762.html