programing

공변 반환 유형이란 무엇입니까?

nasanasas 2020. 8. 30. 08:41
반응형

공변 반환 유형이란 무엇입니까?


Java의 공변 반환 유형은 무엇입니까? 일반적으로 객체 지향 프로그래밍에서?


공변 반환은 메서드를 재정의 할 때 재정의 된 메서드의 반환 유형이 재정의 된 메서드의 반환 유형의 하위 유형이 될 수 있음을 의미합니다.

예제를 통해이를 명확히하기 위해 일반적인 경우는 Object.clone()-형식을 반환하도록 선언됩니다 Object. 다음과 같이 자신의 클래스에서이를 재정의 할 수 있습니다.

public class MyFoo
{

   ...

   // Note covariant return here, method does not just return Object
   public MyFoo clone()
   {
       // Implementation
   }
}

여기서 이점은 MyFoo 객체에 대한 명시 적 참조를 보유하는 모든 메서드가 clone()반환 값이의 인스턴스임을 (캐스팅하지 않고) 호출 하고 알 수 있다는 것 입니다 MyFoo. 공변 반환 유형이 없으면 MyFoo의 재정의 된 메서드가 반환되도록 선언해야합니다. Object따라서 호출 코드는 메서드 호출의 결과를 명시 적으로 다운 캐스트해야합니다 (양측이 "알고"있다고 ​​생각하더라도 항상 MyFoo의 인스턴스 일 수 있다고 생각). ).

특별한 것은 없으며 clone()재정의 된 메서드는 공변 반환을 가질 수 있습니다. 여기서는 이것이 종종 유용한 표준 메서드이기 때문에 예제로 사용했습니다.


다음은 또 다른 간단한 예입니다.

Animal 수업

public class Animal {

    protected Food seekFood() {

        return new Food();
    }
}

Dog 수업

public class Dog extends Animal {

    @Override
    protected Food seekFood() {

        return new DogFood();
    }
}

아래와 같이 DogseekFood()메서드 의 반환 유형 DogFood-의 하위 클래스 로 수정할 수 Food있습니다.

@Override
protected DogFood seekFood() {

    return new DogFood();
}

그것은 완벽하게 합법적 인 재정의이며 DogseekFood()메서드 의 반환 유형은 공변 반환 유형으로 알려져 있습니다.


JDK 1.5 릴리스부터 공변 유형이 Java에 도입되었습니다. 간단한 사례로 설명 하겠습니다. 함수를 재정의 할 때 함수는 대부분의 책에서 읽을 수있는 동작 을 변경할 수 있지만 {저자}가 놓친 부분은 반환 유형도 변경할 수 있다는 것입니다. 아래 링크를 확인하여 메서드의 기본 버전 반환 유형에 할당 할 수있는 한 반환 유형을 변경할 수 있습니다.

So this feature of returning derived types is called COVARIANT...

Can overridden methods differ in return type?


covariant Return types simply means returning own Class reference or its child class reference.

class Parent {
 //it contain data member and data method
}

class Child extends Parent { 
//it contain data member and data method
 //covariant return
  public Parent methodName() {
     return new Parent();
          or 
     return Child();
  }

}

Covariant return type specifies that the return type may vary in the same direction as the subclass

class One{  
    One get(){return this;}  
}  

class Two extends One{  
  Two get(){return this;}  

void message(){
  System.out.println("After Java5 welcome to covariant return type");
}  

public static void main(String args[]){  
    new Two().get().message();  
}  
}

Before Java 5, it was not possible override any method by changing the return type. But now, since Java5,

it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type.


  • It helps to avoid confusing type casts present in the class hierarchy and thus making the code readable, usable and maintainable.
  • We get a liberty to have more specific return types when overriding
    methods.

  • Help in preventing run-time ClassCastExceptions on returns

reference: www.geeksforgeeks.org


  • The covariant return type in java, allows narrowing down return type of the overridden method.
  • This feature will help to avoid down casting on the client side. It allows programmer to program without the need of type checking and down casting.
  • The covariant return type always works only for non-primitive return types.
interface Interviewer {
    default Object submitInterviewStatus() {
        System.out.println("Interviewer:Accept");
        return "Interviewer:Accept";
    }
}
class Manager implements Interviewer {
    @Override
    public String submitInterviewStatus() {
        System.out.println("Manager:Accept");
        return "Manager:Accept";
    }
}
class Project {
    public static void main(String args[]) {
        Interviewer interviewer = new Manager();
        interviewer.submitInterviewStatus();
        Manager mgr = new Manager();
        mgr.submitInterviewStatus();
    }
}

Other example is from Java,

UnaryOperator.java

@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {

    /**
     * Returns a unary operator that always returns its input argument.
     *
     * @param <T> the type of the input and output of the operator
     * @return a unary operator that always returns its input argument
     */
    static <T> UnaryOperator<T> identity() {
        return t -> t;
    }
}

Function.java

@FunctionalInterface
public interface Function<T, R> {

    ........
    ........
    ........
    ........

    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

Before Java5, it was not possible to override any method by changing the return type. But now, since Java5, it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type.

참고URL : https://stackoverflow.com/questions/1882584/what-is-a-covariant-return-type

반응형