java第八章(2)抽象类

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值