I do potih assignments from Reshebnik and it is on the third point I was knocked out of a rut.

Create a class object Kitten using classes Animal, Cat. Methods:

  1. display the name on the console

  2. give voice

  3. give birth to offspring (create your own kind).
public class Main { public static void main(String[] args) { Cat cat = new Cat(); Kitten kitten = cat.giveBirth(); System.out.println(kitten); cat.printName(); } } interface Mother { <T extends Animal> Kitten giveBirth(); } abstract class Animal { protected String name; abstract void say(); public void printName() { System.out.printf("My name is %s\n", name); } } class Cat extends Animal implements Mother { public Cat() { name = "Cat"; } @Override public <T extends Animal> Kitten giveBirth() { return new Kitten(); } @Override public void say() { System.out.printf("Meow\n"); } } class Kitten extends Animal { public Kitten() { name = "Kitten"; } @Override public void say() { System.out.printf("Meow\n"); } } 

How to make it work from the output in main, that is, something like this:

 public class Main { public static void main(String[] args) { Cat cat = new Cat("nameCat"); cat.say(); System.out.printf(cat.giveBirth()); Cat catTwo = new Cat("nameCatTwo"); catTwo.say(); System.out.printf(catTwo.giveBirth()); } } 

And did I understand the third point? What should he output? Almost 6 am, I do not understand anything. And how to correctly override for each class the methods equals() , hashCode() , toString() ?

  • If you are given an exhaustive answer, mark it as accepted ^^ " - Suvitruf

1 answer 1

Your Kitten class is at least incorrectly implemented. In general, he as a whole is not needed, as the kitten is also a cat, only a small one.

But if you really want a separate class for a kitten, then you need to inherit it from Cat , not Animal .

The implementation of the cat is also strange: class Cat extends Animal implements Mother . The cat is not a mother, he can not give birth. Or did the cat mean exactly like a female?

Plus, you implement this interface in a cat, and not in the base class Animal . In this case, for example, if you want to create a class for the dog Dog , will you also implement this interface there? In an amicable way, such things need to be implemented as high as possible in the class hierarchy.