从头认识java-7.1 抽象类与抽象方法

这一章节我们来聊一下抽象类与抽象方法。

1.什么是抽象类与抽象方法。

在类和方法前面加上abstract,这个类或者方法就是抽象类

package com.ray.ch07;

public class Test {

}

abstract class Instument {
	public abstract void Play();
}

2.抽象类与抽象方法的特性

抽象类:

(1)抽象类里面不是全都是抽象方法,有的方法也是可以是实现的

(2)具有抽象方法的必然是抽象类

(3)不能实例化

抽象方法:

(1)没有实现的使用abstract标注的方法

(2)继承抽象类的子类必须实现抽象方法


3.实例对比

下面我们给出两个例子,来对比抽象类与普通类的区别。

package com.ray.ch07;

public class Test {
	public void tune(Instrument instrument) {
		instrument.Play();
	}

	public void tune(Instrument[] instruments) {
		for (int i = 0; i < instruments.length; i++) {
			tune(instruments[i]);
		}
	}

	public static void main(String[] args) {
		Test test = new Test();
		Instrument instrument = new Instrument();
		Wind wind = new Wind();
		Bass bass = new Bass();
		Instrument[] instruments = { instrument, wind, bass };
		test.tune(instruments);
	}
}

class Instrument {
	public void Play() {
		System.out.println("instrument play");
	}
}

class Wind extends Instrument {
	@Override
	public void Play() {
		System.out.println("wind play");
	}
}

class Bass extends Instrument {
	@Override
	public void Play() {
		System.out.println("bass play");
	}
}

上面的例子我们没有使用抽象类,这里面我们可以new Instrument,但是就会出现一个问题,因为在大部分编码的时间里面,Instrument这个类我们是不需要new出来的,而且instrument里面的play一般是不需要调用,因此,play这个方法只需要有就可以,并不需要花心思实现,上面的new,只不过是我做例子给大家看而已。

基于这个情况,我们使用抽象类来抽象instrument和play即可。这样我们就可以省下实现的时间,而且也可以通过这个继承和以后说的接口来实现多态。

package com.ray.ch07;

public class Test {
	public void tune(Instrument instrument) {
		instrument.Play();
	}

	public void tune(Instrument[] instruments) {
		for (int i = 0; i < instruments.length; i++) {
			tune(instruments[i]);
		}
	}

	public static void main(String[] args) {
		Test test = new Test();
		// Instrument instrument = new Instrument();//error
		Wind wind = new Wind();
		Bass bass = new Bass();
		Instrument[] instruments = { wind, bass };
		test.tune(instruments);
	}
}

abstract class Instrument {
	public abstract void Play();
}

class Wind extends Instrument {
	@Override
	public void Play() {
		System.out.println("wind play");
	}
}

class Bass extends Instrument {
	@Override
	public void Play() {
		System.out.println("bass play");
	}
}

大部分的情况就像我们上面展示的,Instrument只是作为抽象的一个类,而play这个方法也是抽象出来,子类必须实现它,然后可以直接使用Instrument来指向这些子类。

而且,我们可以从代码上面看到,Instrument是不可以new的。


总结:这一章节我们简单讨论了一下抽象类与抽象方法。



这一章节就到这里,谢谢。

-----------------------------------

目录




  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值