And again I step on a rake, moving from theory to practice.
There is an abstract class Animal
. This class has a makeNoise(),
method that displays the message "I am an animal!". There are also classes Cat
and Dog
, which are inherited from the super-class Animal
. In each of them, I overridden the method makeNoise()
. Now, depending on whether the cat was created or the dog, the method displays "Meow" or "Woof."
But! Let's say it became necessary for an object of type Cat
call the method makeNoise()
, but not its own method, which gives us "Meow", but the method of the super-class, which tells us "I am an animal". How to implement it? My attempts below, the result is 0, the overridden method is called :(
public class Main { public static void main(String[] args) { /*Объекты типа animal*/ Animal cat = new Cat("Маруся"); Animal dog = new Dog("Шарик"); /*Объекты своих собственных типов*/ Cat cat2 = new Cat("Маруся 2"); Dog dog2 = new Dog("Шарик 2"); System.out.println("-------------------"); cat.makeNoise(); cat2.makeNoise(); } } public abstract class Animal { private String name; public void setName(String name) { this.name = name; } public String getName() { name = this.name; return name; } public void makeNoise() { System.out.println("Я животное!!11!!"); } } public class Cat extends Animal { public Cat(String name) { this.setName(name); System.out.println("Новая кошка создана. Ее имя: " + getName()); } @Override public void makeNoise() { System.out.println(getName() + " Сказала: " + "Мяу мяу"); } } public class Dog extends Animal { public Dog(String name) { this.setName(name); System.out.println("Новая собака создана. Ее имя: " + getName()); } @Override public void makeNoise() { System.out.println(getName() + " Сказала: " + "Гав гав"); } }
PS Tell me, please, is there a polymorphism in the example I described?