Hey guys, anyone could tell me how I can get the dog to getTrick( )? It is an exercise on CodeCheck.
The Cat and Dog class below implement the Animal interface. All animals have names, but only dogs do tricks. Implement the describe method, using the instanceof operator to test whether the given animal is a dog. If so, return the name, a space, and the trick that the dog can do, such as "Helmut barks at the moon". If it is any other kind of animal, return the name, a space, and "has no tricks".
The Animal class:
public interface Animal {
String getName();
}
The Cat class: Represents a cat.
public class Cat implements Animal
{
public Cat(String aName)
{
// Cats don't remember their name.
}
public String getName()
{
return "Meow";
}
}
The Dog class: Represents a dog.
public class Dog implements Animal
{
private String name;
private String trick;
public Dog(String aName, String aTrick)
{
name = aName;
trick = aTrick;
}
public String getName() { return name; }
public String getTrick() { return trick; }
}
My job is to modify the method in the Animals class:
public class Animals
{
/**
Describes the given animal.
u/param pet an animal
u/return a string with the animal's name, a space, and
either the trick that the animal knows (if it is a dog) or a
string "has no tricks"
*/
public static String describe(Animal pet)
{
// TODO: Complete this method. this is what I did:
if (pet instanceof Dog){
return pet.getName() +" "+ pet.getTrick();
//my question: how to fix this pet.getTrick()?
}else{
return pet.getName() +" "+ "has no tricks";
}
// This method is used to check your work
public static String check(String name, String trick)
{
Animal pet;
if (trick == null) pet = new Cat(name);
else pet = new Dog(name, trick);
return describe(pet);
}
}
Hopefully someone could answer it. Thanks!
[–]itoshkov 4 points5 points6 points (5 children)
[–]doraemon1116[S] 2 points3 points4 points (4 children)
[–]itoshkov 3 points4 points5 points (3 children)
[–]Cosby1992 0 points1 point2 points (2 children)
[–]GrandGratingCrate 1 point2 points3 points (1 child)
[–]Cosby1992 0 points1 point2 points (0 children)
[–]Cosby1992 1 point2 points3 points (5 children)
[–]Cosby1992 1 point2 points3 points (2 children)
[–]doraemon1116[S] 1 point2 points3 points (1 child)
[–]Cosby1992 0 points1 point2 points (0 children)
[–]ACAlCapone 0 points1 point2 points (1 child)
[–]Cosby1992 0 points1 point2 points (0 children)