java協變返回類型
協變返回類型 (Covariant return type)
The covariant return type is that return type which may vary in parent and child class (or subclass).
協變量返回類型是該返回類型,在父類和子類(或子類)中可能有所不同。
Before JDK5 java does not support covariant return type it means (parent return type and child return must be same).
在JDK5 Java不支持協變返回類型之前,這意味著(父返回類型和子返回必須相同)。
In JDK5 onwards java supports covariant return type it means (parent return type and child return can vary if we define).
從JDK5開始,Java支持協變返回類型 (如果我們定義,則父返回類型和子返回可以不同)。
The covariant return type is useful in method overriding when we override a method in the derived class (or subclass) then return type may vary depending on JDK (Before JDK5 return type should be same and after or JDK5 we can consider return type can vary).
當我們重寫派生類(或子類)中的方法時, 協變量返回類型在方法重寫中很有用,然后返回類型可能會因JDK而異(在JDK5返回類型應該相同之前,或者在JDK5之后,我們可以考慮返回類型可以變化) 。
Example -1
例子-1
class ParentClass1{
int a=10,b=20;
public int sum(){
return a+b;
}
}
class ChildClass1 extends ParentClass1{
int c=30, d=40;
public int sum(){
return (c+d);
}
public static void main(String[] args){
ChildClass1 cc1 = new ChildClass1();
ParentClass1 pc1 = new ParentClass1();
int e = cc1.sum();
int f = pc1.sum();
System.out.println("Child class Sum is :"+e);
System.out.println("Parent class Sum is :"+f);
}
}
Output
輸出量
D:\Java Articles>java ChildClass1
Child class Sum is :70
Parent class Sum is :30
Example -2
示例-2
class ParentA {}
class ChildB extends ParentA {}
class Base
{
ParentA demoA()
{
System.out.println("Base class demo");
return new ParentA();
}
}
class Subclass extends Base
{
ChildB demoB()
{
System.out.println("Subclass demoB");
return new ChildB();
}
}
class MainClass
{
public static void main(String args[])
{
Base b = new Base();
b.demoA();
Subclass sub = new Subclass();
sub.demoB();
}
}
Output
輸出量
D:\Java Articles>java MainClass
Base class demo
Subclass demoB
翻譯自: https://www.includehelp.com/java/covariant-return-type.aspx
java協變返回類型