这一章节我们来聊一下抽象类与抽象方法。
1.什么是抽象类与抽象方法。
在类和方法前面加上abstract,这个类或者方法就是抽象类
package com.ray.ch07;
public class Test {
}
abstract class Instument {
public abstract void Play();
}抽象类:
(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");
}
}基于这个情况,我们使用抽象类来抽象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是不可以new的。
总结:这一章节我们简单讨论了一下抽象类与抽象方法。
这一章节就到这里,谢谢。
-----------------------------------
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/raylee2007/article/details/49717981