8.2抽象类
1).抽象类与抽象方法
抽象类是以修饰符abstract 修饰的类,定义抽象类的语法格式如下:
abstract class 类名
{
声明成员变量;
返回值的数据类型 方法名( 参数表 )
{
......
}
abstract 返回值的数据类型 方法名( 参数表 ); ------抽象方法,在抽象方法里,不能定义方法体
}
抽象方法中的方法分为两种,一种是以前介绍的一般方法,另一种是"抽象方法".
抽象方法没有方法方法体,用";".
抽象的子类必须实现父类中的所有抽象方法,或者将自己也声明为抽象的.
一个abstract 类不能用final 来修饰.
2).抽象类的应用
eg:
abstract class Shape {
protected String name;
public Shape( String xm)
{
name = xm;
System.out.print("名称" + name);
}
abstract public double getArea( ); //声明抽象方法
abstract public double getLength( );声明抽象方法
}
public class Circle extends Shape
{
private 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;
}
}
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle( String shapename, double width, double height )
{
super( shapename );
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
@Override
public double getLength() {
return 2 * (width + height );
}
}
public class app8_10 {
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() );
}
}
程序运行结果:
名称长方形;面积=66.95周长=33.6
名称圆;面积=326.68559999999997;周长=64.056