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

来源:互联网 发布:舞台灯光软件 编辑:程序博客网 时间:2024/06/05 19:51

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

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 {@Overridepublic void Play() {System.out.println("wind play");}}class Bass extends Instrument {@Overridepublic 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();//errorWind 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 {@Overridepublic void Play() {System.out.println("wind play");}}class Bass extends Instrument {@Overridepublic void Play() {System.out.println("bass play");}}

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

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


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



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

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

目录




0 0
原创粉丝点击