Shape:
Shape:
package Area; /** * 求面積 * @author Administrator * */ public abstract class Shape { public String getName(){ return this.getClass().getName();//獲得類名稱 } public abstract double getArea(); }
Circle:
package Area; public class Circle extends Shape{ private double radius; public Circle(){ } public Circle(double radius){ this.radius=radius; } public double getArea(){//主要是抽象的實現 return Math.PI*Math.pow(radius,2); } }
Triangle:
package Area; public class Triangle extends Shape{ private double x; private double y; public Triangle(){ } public double getArea(){ return (x*y)/2; } public Triangle(double x,double y){ this.x=x; this.y=y; } }
Test:
package Area; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Circle circle = new Circle(1); System.out.println("the shape is:" + circle.getName()); System.out.println("the Area: "+circle.getArea()); Shape tri=new Triangle(1,1); System.out.println("the shape is:" +tri.getName()); System.out.println("the shape is:" + tri.getArea()); } }
focus :
在抽象类中,可以定义抽象方法,用abstrat修饰,包含抽象方法的类一定是抽象类,而抽象类不一定包含抽象方法
抽象类是不能直接被实例化的,如果要获得该类的实例,可以使用静态方法传剪其类对象,