i'm studying Java and they gave me an exercise which i'm really struggling with. I'll give you the full exercise (it's translated from my native language) instead of explaining it, so you can understand it. I really can't understand how should i do it. I don't pretend the full code (even tho i'd appreciate that, since a well made code could help me improve and better understand how things should be done), but at least i'd like to know where should i start looking for the solution, cause right now i'm hitting a wall, and it hurts.
My first idea was to override the .equals method, but that doesn't seems right. I thought i could make a subclass but in the example they are using the same class for both the main instance and the 3 derived instances, so that's a no.
Exercise :
Create an Animal class, characterized in this way:
- Number Of Legs
- type (Birds, Cats, etc.)
- average weight
Two animals are considered equal if they have the same number of legs, they belong to the same type and have the same average weight. The class must implement three methods, which allow to convert the Animal so that only one of the characteristics is compared (one method for each characteristic).
Example :
Animal cat = new Animal (4, "Cat", 5);
Animal dog = new Animal (4, "Dog", 5);
Animal catNumberOfLegs = cat.compareNumberOfLegs();
Animal catType = cat.compareType ();
Animal catWeigth = cat.compareWeigth();
Animal dogNumberOfLegs = dog.compareNumberOfLegs ();
Animal dogType = dog.compareType ();
Animal dogWeigth = dog.compareWeigth ();
System.out.println (cat.equals (dog)); // false
System.out.println (catNumberOfLegs.equals (dogNumberOfLegs)); // true
System.out.println (catType.equals (dogType)); // false
System.out.println (catWeigth.equals (dogWeigth)); // true
------------
The values of the variables must remain unchanged.
Java is an object-oriented language: remember it!
EDIT : I'm editing this cause i see some confusion in the comments, don't know if it's cause the exercise is written poorly or if it's cause of the translation.
The point is, i have two instances of Animal class. One is called Cat, the other is called Dog. I have this 3 separate methods to implements that, when used on an instance, return me a new instance that will only take one of the variables into account when using .equals(). Let's take the method "compareNumberOfLegs ();" as an example. Animal dogTWO = dog.compareNumberOfLegs (); Animal catTWO = cat.compareNumberOfLegs (); This means that "dogTWO" will be a new instance that will mantain everything of "dog", but if compared to "catTWO" using .equals(), i'll get 'True' cause only "numberOfLegs" will be compared.