JavaRush /Java Blog /Random EN /Pet cat = new Cat() - what methods can the "cat" variable...
vtimk
Level 17

Pet cat = new Cat() - what methods can the "cat" variable use?

Published in the Random EN group
Dear Java people, let’s say there is code in which a method in an inherited class is overridden: class Pet { String name; String age; String getString() { return "Домашнее животное"; } } class Cat extends Pet { String getString() { return "Кот Рыжик"; } } public static void main(String[] args) { Pet cat = new Cat(); cat.getString(); } please tell me which version of the getString() method will be called for the cat variable? I read in lectures that you can call methods of an object only if they are present in the class that was used as a reference type to the object, regardless of the actual type of the object. Does this mean that in this case the method from the Pet class will be called, or in the case of overriding the method, the method from the object class will be called? Thank you.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION