天若有情

到教堂忏悔,愿主安抚我罪恶的心灵......
posts - 4, comments - 35, trackbacks - 0, articles - 24

接口回调(接口引用)及类的引用

Posted on 2008-08-07 01:49 freedoom 阅读(556) 评论(0)  编辑  收藏 所属分类: JAVA技术
 

package dao;

class Father{

    void method(){

       System.out.println("Father method called.....");

    }

}

class Son extends Father{

    void method(){

       System.out.println("Son method called.....");

    }

}

publicclass TestAbstract{

    publicstaticvoid main(String args[]){

       Father f;

       Son son=new Son();

       f=son;

//     Father f=new Son();

       f.method();

    }

}

为什么可以用Father f=new Son();

因为Father的范围比Son的范围大,编辑器会帮助我们将子类的类型的自动转换为父类的类型,这即是父类的引用,子类的对象,

注意:这里子类Son已经重写了父类的method()方法,所以当运行f.method();时调用的是子类的方法,所以这里可以得出两点结论,即:

Father f=new Son();运行时:

1.)是父类的引用,子类的对象,实际运行时调用的是被子类重写的方法。

2.)子类重写父类的方法,只能重写父类公共的、非静态的方法。

同理)

以下是接口引用的问题:注意其中的区别。

接口引用

static void Main(string[] args)
{
    IBankAccount venusAccount = 
new SaverAccount();
    IBankAccount jupiterAccount = 
new CurrentAccount();
    venusAccount.PayIn(200);
    jupiterAccount.PayIn(500);
    Console.WriteLine(venusAccount.ToString());
    jupiterAccount.PayIn(400);
    jupiterAccount.Withdraw(500);
    jupiterAccount.Withdraw(100);
    Console.WriteLine(jupiterAccount.ToString());

}


  请注意开头两句,我们把它们声明为IBankAccount(这是一个接口)引用的方式,而没有声明为类的引用,为什么呢?因为,这样我们就可以让它指向执行这个接口的任何类的实例了,比较灵活。这也就是接口回调。但这也有个缺点,如果我们要执行不属于接口的方法,比如这里重载的ToString()方法,就要先把接口的引用强制转换成合适的类型了。

接口回调的例子:

interface People{

   void peopleList();

}

class Student implements People{

   public void peopleList(){

    System.out.println("I’m a student.")

}

}

class Teacher implements People{

  public void peopleList(){

    System.out.println("I’m a teacher.");

}

}

public class Example{

  public static void main(String args[]){

    People a;             //声明接口变量

a=new Student();      //实例化,接口变量中存放对象的引用

a.peopleList();        //接口回调

a=new Teacher();     //实例化,接口变量中存放对象的引用

a.peopleList();       //接口回调

}

}

       结果:

I’m a student.

I’m a teacher