在java中覆盖具有不同返回类型的方法?
我读过一本书,它说我可以覆盖一个方法,如果它有相同的签名。 根据书中方法的签名是Method_Name + Parameters传递。
根据本书,我可以覆盖具有不同返回类型的方法。 实际上是否可以在Java中覆盖具有不同返回类型的方法? 因为我在网上做了一些搜索,我发现人们说要覆盖一个方法,返回类型也应该是相同的。
根据该书,它还说当我们尝试使用相同的方法名称和参数但不同的返回类型重载方法时,java将抛出编译错误,因为签名仅表示方法名称和参数。 如果这是真的,我们应该能够覆盖具有不同返回类型的方法。
请帮我理解这个。 提前致谢。
您可以返回不同的类型,只要它与重写方法的返回类型兼容即可。 兼容意味着:它是被重写方法返回的类或接口的子类,子接口或实现。
这是合乎逻辑的。 如果一个方法返回一个Animal,并且你的派生类返回一个Cow,那么你就不会破坏超类方法的契约,因为一个Cow就是一个Animal。 如果派生类返回香蕉,那就不再正确,因为香蕉不是动物。
你的父母class向外界承诺。 例如,方法:
public Price calculatePrice(Items[] items)
。
它告诉全世界期待价格。
如果在子类中增强该function,则仍需要保留父类的原始承诺。
您可以添加重载的计算方法:
public Price calculatePrice(Items[] items, Integer minimumCharge)
。
您甚至可以使用更具体的返回类型来改善父母的承诺:
public AccuratePrice calculatePrice(Items[] items, Integer minimumCharge)
。
但是你必须至少返回你父母所承诺的类型。 方法声明中的exception也是如此。
是的,从Java 5开始,它可以称为协变返回类型。 返回类型应该是超类方法返回类型的子级(不允许使用基本类型)。 例
class X implements Cloneable { @Override protected X clone() { try { return (X) super.clone(); } catch (CloneNotSupportedException e) { throw new Error(e); // can never happen } } }
这是一个例子:
class Base { public Number test() { return 0; } } class A extends Base { public Long test() { return 1L; } }
您的overriden方法可以具有相同的类型或原始返回类型的子类型,称为协变返回。
如果将overriden方法的返回类型更改为不是原始类型的子类型的其他类型,则会出现编译时错误。
Yes we can override different return types but they should be subclass. public class Shape { public Shape area(Integer i) { System.out.println("Sape Area"); System.out.println("Integer"); return null; } } package com.oops; public class Circle extends Shape { public Circle area(Integer i) { System.out.println("Circle Area"); System.out.println("int"); return null; } }
// Covariant Overriding public class Parent { public Parent(){} String parentName; public Parent(String parentName){ this.parentName=parentName; System.out.println(this.parentName); } public Parent show(){ return new Parent("Parent"); } } public class Child extends Parent{ public Child(){} String name; public Child(String name){ this.name=name; System.out.println(this.name); } public Child show(){ return new Child("Child"); } } public class Main { public static void main(String[] args) { Parent parent=new Child(); parent.show(); Parent parent1=new Parent(); parent1.show(); } }