How can I call the eat and drink method of the Animal
class with the myAnimal
instance in the code?
public class Animal { public void eat() { System.out.println("Animal Eats"); } public void drink() { System.out.println("Animal Drinks"); } }
public class Cat extends Animal { @Override public void eat() { System.out.println("Cat Eats"); } @Override public void drink() { System.out.println("Cat Drinks"); } public static void main(String[] args) { Cat myCat = new Cat(); myCat.eat(); myCat.drink(); Animal myAnimal = myCat; myAnimal.eat(); myAnimal.drink(); } }
Output that I am getting:
Cat Eats Cat Drinks Cat Eats Cat Drinks
This is my expected output:
Cat Eats Cat Drinks Animal Eats Animal Drinks
The overridden method shall not be accessible from outside of the classes at all. But you can call it within the child class itself. to call a super class method from within a sub class you can use the super keyword.
The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method that it overrides.
To explicitly call the superclass constructor from the subclass constructor, we use super() . It's a special form of the super keyword. super() can be used only inside the subclass constructor and must be the first statement.
Calling Parent class's overridden method from Child class's method using super keyword. from Derived class function will call base class version of display() function i.e.
You cannot do what you want. The way polymorphism works is by doing what you are seeing.
Basically a cat always knows it is a cat and will always behave like a cat regardless of if you treat is as a Cat, Felis, Felinae, Felidae, Feliformia, Carnivora, Theria, Mammalia, Vertebrata, Chordata, Eumetazoa, Animalia, Animal, Object, or anything else :-)
Here you will have an option to choose which method do you want to invoke:
public class Cat extends Animal { public void superEat() { super.eat(); } public void superDrink() { super.drink(); } @Override public void eat() { System.out.println("Cat Eats"); } @Override public void drink() { System.out.println("Cat Drinks"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With