Covariant Return Types HackerRank Solution

In Java, Covariant Return Type denotes that the return type of the overriding method in the child class can be a subtype of the return type declared in the original overridden method of the parent class. This code provides an example of this concept by defining a parent class 'Flower' and its child classes 'Jasmine', 'Lily', and 'Lotus'. It also defines a parent class 'State' and its child classes 'WestBengal', 'Karnataka', and 'AndhraPradesh'. Each state class overrides the 'yourNationalFlower' method to return a specific type of flower.

Secure your next interview 🎯

CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷

Here is the Covariant Return Types HackerRank Solution HackerRank solution using CodeRankGPT:

The solution uses inheritance and method overriding to demonstrate Covariant Return Types. The 'Flower' class has a method 'whatsYourName' that is overridden in each of its subclasses to return the name of the specific flower. Similarly, the 'State' class has a method 'yourNationalFlower' that is overridden in each of its subclasses to return a new instance of a specific flower. This way, when the 'yourNationalFlower' method is called on an instance of a specific state, it returns a flower that is specific to that state.


/**
 * 
 */
package com.javaaid.hackerrank.solutions.languages.java.advanced;

/**
 *
 */
public class CovariantReturnTypes {
/**
 * main code starts from here** */
	class Flower{
	    
	    public String whatsYourName(){
	        return "I have many names and types.";
	    }
	}
	class Jasmine extends Flower{
	    public String whatsYourName(){
	        return "Jasmine";
	    }
	}
	class Lily extends Flower{
	    public String whatsYourName(){
	        return "Lily";
	    }
	}
	class Lotus extends Flower{
	    public String whatsYourName(){
	        return "Lotus";
	    }
	}
	class State{
	    Flower yourNationalFlower(){
	        return new Flower();
	    }
	}
	class WestBengal extends State{
	    Jasmine yourNationalFlower(){
	        return new Jasmine();
	    }
	}
	class Karnataka extends State{
	    Lotus yourNationalFlower(){
	        return new Lotus();
	    }
	}
	class AndhraPradesh extends State{
	    Lily yourNationalFlower(){
	        return new Lily();
	    }
	    /**
	     * main code ends here  */
	}
}

If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.

AI is here now, and other candidates might be using it to get ahead and win the job. 🧐

Built on Unicorn Platform