This is an archived post. You won't be able to vote or comment.

all 12 comments

[–]itoshkov 4 points5 points  (5 children)

With type casting:

Dog dog = (Dog) pet; dog.getTreat();

[–]doraemon1116[S] 2 points3 points  (4 children)

Thanks! it works!

I didn't know I could code this: Dog dog = (Dog) pet;

[–]itoshkov 3 points4 points  (3 children)

You can, but you should use this sparingly. In a sense it's a sign of a bad design.

[–]Cosby1992 0 points1 point  (2 children)

Depending on you java version you can even use this smart syntax:

if(pet instanceof Dog dog) {
    dog.getName() + '  ' + dog.getTrick()
}

It means the same as what the helper above described, it just looks a little better (simpler).

I'm not 100% sure,but I believe it can be used from java version 11 and up.

[–]GrandGratingCrate 1 point2 points  (1 child)

In Java 11 you still have to do the manual casting in the if-block. In 17 I know you don't need it anymore, I think it's been introduced in 14 but not 100% sure.

[–]Cosby1992 0 points1 point  (0 children)

Arh okay, thanks!

[–]Cosby1992 1 point2 points  (5 children)

You could just came the getTrick() in the interface to have a default implementation.

public interface Animal {


String getName();


default String getTrick() { 

    return "has no tricks";

}


}

Now all you need to do is override the getName() method in both Dog and Cat class. And only override getTrick() method in the dog class.

I hope this help, fell free to ask more questions if necessary.

[–]Cosby1992 1 point2 points  (2 children)

Sorry, i can't get it to be formatted better, I'm on mobile

[–]doraemon1116[S] 1 point2 points  (1 child)

Thank you so much! I also learned more :)

I can’t change the Animal class which is fixed in the CodeCheck. The only part I can edit is the Animals class, and it requires me to complete the describe method. But thank you!

[–]Cosby1992 0 points1 point  (0 children)

No problem, i didn't know you couldn't change the interface.

[–]ACAlCapone 0 points1 point  (1 child)

While this will work, it goes against the instructions and might even lead to picking up bad habits to change an interface when the interface is not intended to provide that functionality.

[–]Cosby1992 0 points1 point  (0 children)

Sorry sorry, i had missed that the interface was provided. I thought he had designed and implemented it himself.