一、抽象类
类用abstract修饰的,且至少有个抽象方法。
1 /**
2 * 抽象类
3 */
4 public abstract class Simple {
5 public String aMethod() {
6 return "in aMethod";
7 }
8
9 public abstract String bMethod();
10
11 /*
12 * Simple simple = new Simple();
13 * 因为Simple是一个抽象类,它类中有个方法缺少定义,所以无法实例化Simple类
14 * Simple simple = new Simple();//是非法的
15 * 但Simple simple;是合法的,但没有意义(现在)。
16 */
17
18 /*
19 * 抽象类的作用:
20 * 通过继承来扩充它,子类可以对抽象方法提供自己的定义。
21 * 例子:类Child1,Child2是Simple的子类
22 */
23
24 public class Child1 extends Simple {
25 @Override
26 public String bMethod() {
27 return "in bMethod of Child1";
28 }
29
30 }
31
32 public class Child2 extends Simple {
33
34 @Override
35 public String bMethod() {
36 return "in bMethod of Child2";
37 }
38
39 }
40
41 /*
42 * 下面的定义将有意义:
43 * Simple simple ;
44 * int code;
45 if(1 == code){
46 simple = new Child1();
47 }
48 else if(2 == code){
49 simple = new Child2();
50 }
51 simple.bMethod();
52 */
53
54 }
二、接口
1、接口中所有方法都是抽象的,因此不能被实例化。
2、如果一个类实现了接口中的部分方法,那么这个类必定是抽象类,因此不能被实例化。