Java中abstract类和abstract方法

用关键字abstract修饰的类称为abstract类(抽象类)。如:

abstract  class A  {
      abstract int min(int x,int y);
}

用关键字abstract修饰的方法称为abstract方法(抽象方法)

对于abstract方法,只允许声明,不允许实现,而且不允许使用finalabstract同时修饰一个方法,例如:

abstract int min(int x,int y);

理解abstract

1抽象类可以抽象出重要的行为标准,该行为标准用抽象方法来表示。即抽象类封装了子类必需要有的行为标准。

2抽象类声明的对象可以成为其子类的对象的上转型对象,调用子类重写的方法,即体现子类根据抽象类里的行为标准给出的具体行为。

abstract class  GirlFriend  //抽象类封装了两个行为标准
{
	abstract void speak();
	abstract void cooking();
}

class ChinaGirlFriend extends GirlFriend 
{
	void speak(){
		System.out.println("你好!");
	}
	void cooking(){
		System.out.println("水煮鱼!");
	}
}

class AmericanGirlFriend extends GirlFriend
{
	void speak(){
		System.out.println("hello !");
	}
	void cooking(){
		System.out.println("roast beef!");
	}
}

class Boy
{
	GirlFriend friend;
	void setGirlfriend(GirlFriend f){
		friend = f;
	}
	void showGirlFriend(){
		friend.speak();
		friend.cooking();
	}
}

public class Example5_11
{
	public static void main(String args[]){
		GirlFriend girl = new ChinaGirlFriend();  //girl是上转型对象
		Boy boy = new Boy();
		boy.setGirlfriend(girl);
		boy.showGirlFriend();

		girl = new AmericanGirlFriend();
		boy.setGirlfriend(girl);
		boy.showGirlFriend();
	}
}

 

abstract class 机动车 
{
	abstract void 启动();
	abstract void 加速();
	abstract void 刹车();
}

class 手动挡轿车 extends 机动车
{
	void 启动(){
		System.out.println("踏下离合器,换到一档。");
		System.out.println("然后慢慢抬起离合器。");
	}
	void 加速(){
		System.out.println("踩油门!");
	}
	void 刹车(){
		System.out.println("踏下离合器,踏下刹车板。");
		System.out.println("然后将挡位换到一档。");
	}
}

class 自动挡轿车 extends 机动车
{
	void 启动(){
		System.out.println("使用前进档。");
		System.out.println("然后轻踩油门。");
	}
	void 加速(){
		System.out.println("踩油门!");
	}
	void 刹车(){
		System.out.println("踏下刹车板。");
	}
}

public class Example5_12
{
	public static void main(String args[]){
		机动车 car = new 手动挡轿车();
		System.out.println("手动挡轿车的操作:");
		car.启动();
		car.加速();
		car.刹车();

		car = new 自动挡轿车();
		System.out.println("自动挡轿车的操作:");
		car.启动();
		car.加速();
		car.刹车();
	}
}

抽象方法的 3 个特征如下:

  1. 抽象方法没有方法体
  2. 抽象方法必须存在于抽象类中
  3. 子类重写父类时,必须重写父类所有的抽象方法


注意:在使用 abstract 关键字修饰抽象方法时不能使用 private 修饰,因为抽象方法必须被子类重写,而如果使用了 private 声明,则子类是无法重写的。

抽象类的定义和使用规则如下:

  1. 抽象类和抽象方法都要使用 abstract 关键字声明。
  2. 如果一个方法被声明为抽象的,那么这个类也必须声明为抽象的。而一个抽象类中,可以有 0~n 个抽象方法,以及 0~n 个具体方法。
  3. 抽象类不能实例化,也就是不能使用 new 关键字创建对象。

 

  • 26
    点赞
  • 79
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

树下一朵云

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值