抽象类的定义及使用
抽象类只是在普通类的基础上扩充了一些抽象方法,抽象方法是只声明未实现
所有抽象方法要用abstract定义,抽象方法的类也要使用abstract定义类,表示抽象类
抽象类就是比普通多了抽象方法而已,
1 abstract class A{ 2 private String msg="www.mldn.cn";//属性 3 public void print(){//方法 4 System.out.println(msg); 5 } 6 //{}为方法体,所有抽象方法上是不包含方法体的 7 public abstract void fun();//抽象方法 8 } 9 class B extends A{//定义抽象类的子类。 10 public void fun(){ 11 System.out.println("hello world"); 12 } 13 } 14 public class Newbegin{ 15 public static void main(String args []) { 16 A a=new B();//实例化子类对象 17 a.fun(); 18 } 19 }
抽象类的使用原则:
1.所有的抽象类必须有子类
2.抽象类的子类(不是抽象类)必须覆写抽象类的所有方法
方法的覆写一定要考虑到权限问题,抽象方法可以使用任意权限,权限尽量都用public
3.抽象类的对象可以用个对象的多态性,子类为其实例化
抽象类,有抽象方法 有子类继承抽象类。子类要覆写抽象类中的抽象方法。
抽象类的相关规定
1.抽象类只比普通多了一些抽象方法,抽象类也有构造方法,实例化子类前,一定要调用父类的构造方法,
范例:在抽象类中定义构造方法。
1 abstract class A{ 2 public A(){ //构造方法 3 this.print();//调用抽象方法 4 } 5 public abstract void print(); //抽象方法 6 } 7 class B extends A{ 8 private int num=100; 9 public B(int num){ 10 this.num=num; 11 } 12 public void print(){ 13 System.out.println(this.num); 14 } 15 } 16 public class Newbegin{ 17 public static void main(String args []) { 18 new B(30);//实例化子类对象。 19 } 20 }
2.抽象类中允许不定义任何的抽象方法,此时抽象类对象依然无法直接实例化处理
3.抽象类不能用final声明,因为抽象类必须有子类,
抽象方法不能使用private定义,因为抽象方法必须被覆写。
4.抽象类分为内部抽象类和外部抽象类可以使用static定义,描述为外部抽象类
范例:观察内部抽象类
1 abstract class A{ 2 public abstract void print(); 3 abstract class B{ 4 public abstract void printB(); 5 } 6 } 7 class X extends A{ 8 public void print(){ 9 10 } 11 class Y extends B{ 12 public void printB(){ 13 14 } 15 } 16 } 17 public class Newbegin{ 18 public static void main(String args []) { 19 20 } 21 }
我们要在外部抽象类上使用了static那么就是语法错误,但内部抽象类加上static就没有错
模板设计模式
1 abstract class Action{ 2 public static final int EAT=1; 3 public static final int SLEEP=5; 4 public static final int WORK=10; 5 public void command(int cmd){ 6 switch(cmd){ 7 case EAT:this.eat();break; 8 case SLEEP:this.sleep();break; 9 case WORK:this.work();break; 10 case EAT+SLEEP+WORK: 11 this.eat(); 12 this.sleep(); 13 this.work(); 14 break; 15 } 16 } 17 //不确定具体的实现,但是行为应该定义好 18 public abstract void eat(); 19 public abstract void sleep(); 20 public abstract void work(); 21 } 22 class Human extends Action{ 23 public void eat(){ 24 System.out.println("人吃饭"); 25 } 26 public void sleep(){ 27 System.out.println("人睡觉"); 28 } 29 public void work(){ 30 System.out.println("人工作"); 31 } 32 } 33 class Pig extends Action{ 34 public void eat(){ 35 System.out.println("猪吃饭"); 36 } 37 public void sleep(){ 38 System.out.println("猪睡觉"); 39 } 40 public void work(){ 41 } 42 } 43 class Robot extends Action{ 44 public void eat(){ 45 System.out.println("机器人吃饭"); 46 } 47 public void sleep(){ 48 } 49 public void work(){ 50 System.out.println("机器人工作"); 51 } 52 53 } 54 public class Newbegin{ 55 public static void main(String args []) { 56 fun(new Human()); 57 fun(new Pig()); 58 fun(new Robot()); 59 } 60 public static void fun(Action action){ 61 action.command(Action.EAT+Action.SLEEP+Action.WORK); 62 } 63 }