【抽象类与接口的应用】

抽象类和接口不能直接实例化,因为其内部包含了各个抽象方法,抽象方法本身都是未实现的方法,所以无法调用。通过对象多态性,子类发生了向上转型之后,所调用的全部方法都是被覆写过了的方法。

  为抽象类实例化:

  [java]

  abstract class A{   // 定义抽象类A

  public abstract void print() ;  // 定义抽象方法print()

  };

  class B extends A { // 定义子类,继承抽象类

  public void print(){        // 覆写抽象方法

  System.out.println("Hello World!!!") ;

  }

  };

  public class AbstractCaseDemo01{

  public static void main(String args[]){

  A a = new B() ;     // 通过子类为抽象类实例化

  a.print() ;

  }

  };

  为接口实例化:

  [java]

  interface A{    // 定义抽象类A

  public abstract void print() ;  // 定义抽象方法print()

  };

  class B implements A {  // 定义子类,继承抽象类

  public void print(){        // 覆写抽象方法

  System.out.println("Hello World!!!") ;

  }

  };

  public class InterfaceCaseDemo01{

  public static void main(String args[]){

  A a = new B() ;     // 通过子类为抽象类实例化

  a.print() ;

  }

  };

  2、抽象类的应用----定义模板

  [java]

  abstract class Person{

  private String name ;       // 定义name属性

  private int age ;           // 定义age属性

  public Person(String name,int age){

  this.name = name ;

  this.age = age ;

  }

  public String getName(){

  return this.name ;

  }

  public int getAge(){

  return this.age ;

  }

  public void say(){      // 人说话是一个具体的功能

  System.out.println(this.getContent()) ; // 输出内容

  }

  public abstract String getContent() ;   // 说话的内容由子类决定

  };

  class Student extends Person{

  private float score ;

  public Student(String name,int age,float score){

  super(name,age) ;   // 调用父类中的构造方法

  this.score = score ;

  }

  public String getContent(){

  return  "学生信息 --> 姓名:" + super.getName() +

  ";年龄:" + super.getAge() +

  ";成绩:" + this.score ;

  }

  };

  class Worker extends Person{

  private float salary ;

  public Worker(String name,int age,float salary){

  super(name,age) ;   // 调用父类中的构造方法

  this.salary = salary ;

  }

  public String getContent(){

  return  "工人信息 --> 姓名:" + super.getName() +

  ";年龄:" + super.getAge() +

  ";工资:" + this.salary ;

  }

  };

  public class AbstractCaseDemo02{

  public static void main(String args[]){

  Person per1 = null ;    // 声明Person对象

  Person per2 = null ;    // 声明Person对象

  per1 = new Student("张三",20,99.0f) ; // 学生是一个人

  per2 = new Worker("李四",30,3000.0f) ;    // 工人是一个人

  per1.say() ;    // 学生说学生的话

  per2.say() ;    // 工人说工人的话

  }

  };

  3、接口的实际应用----指定标准

  [java]

  interface USB{      // 定义了USB接口

  public void start() ;   // USB设备开始工作

  public void stop() ;    // USB设备结束工作

  }

  class Computer{

  public static void plugin(USB usb){ // 电脑上可以插入USB设备

  usb.start() ;

  System.out.println("=========== USB 设备工作 ========") ;

  usb.stop() ;

  }

  };

  class Flash implements USB{

  public void start(){    // 覆写方法

  System.out.println("U盘开始工作。") ;

  }

  public void stop(){     // 覆写方法

  System.out.println("U盘停止工作。") ;

  }

  };

posted @ 2013-10-08 15:45  豆豆逗逗  阅读(153)  评论(0编辑  收藏  举报