I'll use an easy example for the sake of the question.
If I have an Interface say Animal which is like
public interface Animal {
void jump();
}
And I'm creating an object of the interface on the go, like
public class Main {
public static void main(String[] args) {
Animal cat = new Animal() {
@Override
public void jump() {
System.out.println("The cat jumped");
}
public void sleep() {
System.out.println("The cat slept");
}
};
cat.jump();
cat.sleep(); // cannot do that.
}
}
Now, I added the sleep() method to the interface implementation and want that method to be callable from the place where I'm calling cat.jump(). That is what I want. I see that throws an error and I do understand because the object is of type Animal and Animal does not have the sleep() method.
If I do not want to add a new method to the interface, in that case, what other options do I have to be able to call a method that I created in interface implementation?
Catclass thatimplements Animal?