java 接口回调 可以用类替代吗_接口回调(接口引用)及类的引用

packagedao;

classFather{

voidmethod(){

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

}

}

classSonextendsFather{

voidmethod(){

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

}

}

publicclassTestAbstract{

publicstaticvoidmain(String args[]){

Father f;

Son son=newSon();

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 voidMain(string[] args)

{

IBankAccount venusAccount =newSaverAccount();

IBankAccount jupiterAccount =newCurrentAccount();

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值