java转型多态和契约设计

1、类转型
变量支持互相转化,比如int a=(int)3.5,a=3,把小数部分截断
类型可以互相转型,但只限于有继承关系的类
子类可以转换成父类,但是父类不可以转换成子类
类型转换带来的作用就是多态
子类继承父类的所有方法,但子类可以重新定义一个名字,参数和父类一样,这种行为就是重写
子类的方法的优先级高于父类

2、多态
多态的作用:以统一的接口来操纵某一类中不同的对象的动态行为;、
对象之间的解耦

3、契约设计
①契约:规定规范了对象应该包含的行为方法;
②接口定义了方法的名称,参数和返回值,规定了派生类的返回值
③基于接口,利用转型和多态,不影响真正方法的使用,成功的将调用类和被调用类解耦

new接口的同时必须实现接口所有的方法

public class hello{
public static void main (String[] args) {
hey[] as = new hey[4];
as[0] = new ok();
as[1] = new hi();
as[2] = new ok();
as[3] = new hi();
for(int i=0;i<as.length;i++){
as[i].move();
}
for(int i=0;i<as.length;i++){
havelunch(as[i]);
}
havelunch(new ok());//等价为hey a = new hey();havelunch(a)
havelunch(new hi());
havelunch(
new hey(){
public void eat(){
System.out.println(“we can eat”);
}
public void move(){
System.out.println(“we can move”);
}
}
);
}
public static void havelunch(hey a){
a.eat();
}
}
————————————————
public class hi implements hey{
@Override
public void eat() {
System.out.println(“i can eat too”);
}
@Override
public void move() {
System.out.println(“i can move too”);
}
}
————————————
public class ok implements hey{
public void eat(){
System.out.println(“i can eat”);
}
public void move(){
System.out.println(“i can move”);
}
}
——————————————
public interface hey {
public void eat();
public void move();
}
——————————————————————————
i can move
i can move too
i can move
i can move too
i can eat
i can eat too
i can eat
i can eat too
i can eat
i can eat too
we can eat

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值