java协变类型的好处,Java编程中的协变返回类型。

如果两个类处于继承关系中,即如果一个类扩展了另一个类,则在子类中创建超类成员的副本。如果父类和子类都具有相同的方法(例如sample()),则对于子类对象,这两种方法均可用。

现在,如果使用子类对象调用它,则子类中该方法的主体将被执行,并覆盖超类方法。

示例class Super{

public void demo() {

System.out.println("This is the method of the superclass");

}

}

public class Sub extends Super{

public void demo() {

System.out.println("This is the method of the subclass");

}

public static void main(String args[]){

Sub sub = new Sub();

sub.demo();

}

}

输出结果This is the method of the subclass

协变返回类型

直到Java5允许子类方法覆盖超类的两个方法都应具有相同的名称参数和返回类型。

但是,由于Java5处于覆盖状态,所以超类和子类中的方法具有相同的返回类型不是强制性的。这两个方法可以具有不同的返回类型,但是,子类中的方法应返回超类中方法的返回类型的子类型。因此,重载方法相对于返回类型成为变体,并且这些被称为协变返回类型。

示例

如果您观察以下示例,则超类有一个名为demo()的方法,它返回Number类型的值。子类中的方法可以返回Integer类型的值,该值是Number的子类型。此子类型(Integer)被称为协变类型。class Super{

public Number demo(float a, float b) {

Number result = a+b;

return result;

}

}

public class Sub extends Super{

public Integer demo(float a, float b) {

return (int) (a+b);

}

public static void main(String args[]){

Sub sub = new Sub();

System.out.println(sub.demo(25.5f, 89.225f));

}

}

输出结果114

示例class Example{

int data =100;

Example demoMethod(){

return this;

}

}

public class Sample extends Test{

int data =1000;

Sample demoMethod(){

return this;

}

public static void main(String args[]){

Sample sam = new Sample();

System.out.println(sam.demoMethod().data);

}

}

输出结果1000

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值