So, I have 2 classes: Cat and Kitten extends Cat. They have fields (int age, String name) and a constructor. I am trying to create my Functional interface that takes Kitten as input parameter and returns me a Cat (and makes it 2 years elder).
JavaScript
x
@FunctionalInterface
public interface CatToKittenFunction <Kitten, Cat>{
Cat grow(Kitten k);
}
And Main class
JavaScript
public static void main(String[] args) {
Cat smallCat = new Kitten(1, "Push");
Cat oldCat = grow(s -> s.getClass(), (Kitten)smallCat);
System.out.println("oldCat.getClass() = " + oldCat.getClass());
}
private static Cat grow(CatToKittenFunction function, Kitten kitten){
return (Cat) function.grow(kitten);
}
I don’t have an idea where I can change its age and I have ClassCastException as well. What am I do wrong?
Advertisement
Answer
You can try implementing this by using your functional interface :
Below Lambda expression will take Kitten as input and make it’s age 2 year elder
JavaScriptCatToKittenFunction<Kitten, Cat> fn = (Kitten k) ->{
return new Cat(k.age+2,k.name);
};
Call the grow function by passing kitten object and it will returns the Cat incremented age with 2 year elder.
JavaScriptCat oldCat = fn.grow(smallCat);
System.out.println("oldCat.age: " + oldCat.age);
System.out.println("smallCat.age: " + smallCat.age);