/** * @author MyPc 多态 * 多态的概念:父类的引用型变量指向了子类的对象或者接口类型的引用型变量指向了接口实现类的对象
* 此例展示了多态的优点,即多态在形参中能够接收更多类型的数据 */ class Test { public static void print(MyShape myShape){ myShape.getArea(); myShape.getLength(); } //main方法 public static void main(String[] args) { Circle circle=new Circle(4.0); print(circle); Rectanger re=new Rectanger(5.0, 4.0); print(re); } } abstract class MyShape{ public abstract void getArea(); public abstract void getLength(); } //圆形 class Circle extends MyShape{ static final double PI = 3.14; double radius; public Circle(double radius) { // TODO Auto-generated constructor stub this.radius = radius; } @Override public void getArea() { // TODO Auto-generated method stub System.out.println("圆的面积是:"+PI*radius*radius); } @Override public void getLength() { // TODO Auto-generated method stub System.out.println("圆的周长是:"+2*PI*radius); } } class Rectanger extends MyShape{ double width; double height; public Rectanger(double width,double height) { // TODO Auto-generated constructor stub this.width = width; this.height = height; } @Override public void getArea() { // TODO Auto-generated method stub System.out.println("长方形的面积是:"+width*height); } @Override public void getLength() { // TODO Auto-generated method stub System.out.println("长方形的周长是:"+2*(width+height)); } }

  

posted on 2017-05-10 13:39  人生第一步  阅读(197)  评论(0编辑  收藏  举报