抽象类:
- 含有abstract修饰符的class即为抽象类;
- 抽象类可以声明对象,但不能实例化对象,必须靠子类将方法实现;
- 含有abstract方法的类必须为抽象类;
- 但是抽象类中的方法可以不是抽象的;
抽象方法
- 抽象方法不能实例化,即没有方法体(没有{});
- 抽象方法在非抽象子类中需全部重写
- 抽象方法只能存在抽象类和接口中
例
package gt1;
abstract class Shape//抽象类可以声明对象,但不能实例化对象,必须靠子类将方法实现
{
protected String name;
public Shape(String xm)
{
name=xm;
System.out.print("名称:"+name);
}
abstract public double getArea() ;//抽象方法不能实例化,没有{},没有方法体
abstract public double getLength() ;
//抽象方法只能在抽象类里定义
}
package gt1;
public class Circle extends Shape
{
private final double PI=3.14;
private double radius;
public Circle (String shapeName,double r)
{
super (shapeName);
radius=r;
}
public double getArea()
{
return PI*radius*radius;
}
public double getLength()
{
return 2*PI*radius;
}
}
package gt1;
public class Rectangle extends Shape
{
private double width;//定义成员变量
private double height;
public Rectangle (String shapeName,double width,double height)//构造方法
{
super(shapeName);//需给super()方法传入和父类构造方法一样的参数
this.width=width;//将参数值赋给成员变量
this.height=height;
}
public double getArea()//成员方法
{
return width*height;
}
public double getLength()
{
return 2*(width+height);
}
}
package gt1;
public class AbstractClassTest
{
public static void main(String[]args)//主函数
{
Shape rect =new Rectangle("长方形",6.5,10.3);//创建对象并使用构造方法
System.out.print(";面积="+rect.getArea());
System.out.println(";周长="+rect.getLength());
Shape circle=new Circle("圆",10.2);
System.out.print(";面积="+circle.getArea());
System.out.println(";周长="+circle.getLength());
}
}