covariant return type

The phenomenon that the subclass overrides the parent class method during the inheritance process

1. The following example

package net.oschina.tkj.chapter8.returntype;
/**
 * covariant return type
 * @author Freedom
 *
 */
public class Grain {

	public String toString(){
		return "grain";
	}
}

package net.oschina.tkj.chapter8.returntype;
/**
 * At this time, the class does not inherit the Grain class
 * @author Freedom
 *
 */
public class Wheat {

	public String toString(){
		return "wheat";
	}
}

/**
 * Parent class of WheatMilk
 * @author Freedom
 *
 */
public class Milk {

	public Grain process(){
		return new Grain();
	}
}

package net.oschina.tkj.chapter8.returntype;
/**
 * Subclass of Milk
 * @author Freedom
 *
 */
public class WheatMilk extends Milk {

	/**
	 * The subclass inherits the parent class, the subclass redefines a method with the same name as the parent class method but the return value is inconsistent, there will be a call uncertainty compilation error
	 */
	public Wheat process(){
		
		return null;
	}

 

The above code will give an error when compiling:



 Cause of the error: In the process of inheriting the parent class, a subclass declares a method with the same name as the parent class method but a different return value, and there will be call uncertainty.

 

2. Covariant return types

 

2.1 Amend the above list to the following:

package net.oschina.tkj.chapter8.returntype;
/**
 * At this point, the class inherits the Grain class
 * @author Freedom
 *
 */
public class Wheat extends Grain {

	public String toString(){
		return "wheat";
	}
}

 At this point, the Wheat class inherits the Grain class, the Milk class and its subclasses remain unchanged, and the compiler no longer reports an error.

 

2.1 Covariant return types

After Java SE5, the subclass inherits the method of the superclass that rewrites the superclass, and the return type of the subclass rewrite method can be the return type of the superclass method or the subtype of the return type of the superclass method.

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326439701&siteId=291194637