Casting on objects that implement unrelated Java interfaces

class inher1 { public static void main(String...args) { eat i = new ursus(); if(i instanceof eat) System.out.println("Instance of eat"); //Line 1 if((omnivora)i instanceof eat) System.out.println("Instance of eat"); //Line 2 if((omnivora)i instanceof omnivora) System.out.println("Instance of omnivora"); if(((omnivora)i).like_honey)System.out.println("Like Honey Obtained"); } } interface eat //Interface 1 { public void eat(); } interface omnivora //Interface 2 { final public static boolean like_honey = true; } abstract class mammalia implements eat { abstract public void makenoise(); public void eat(){System.out.println("Yummy");} } class ursus extends mammalia implements omnivora { public void makenoise(){System.out.println("Growl");} } class felidae extends mammalia { public void makenoise(){System.out.println("Roar");} } 

This is my hierarchy.

Eat and Omnivora are unrelated interfaces

Mammalia implements the Eat interface

Ursus extends Mammalia implements Omnivora interface

Felidae distributes Mammalia

As you can see, non-interconnected interfaces are all-inclusive and eating, but at the same time, both Line 1 and Line 2 print "Food Instances" and "Instances explicitly" respectively.

Can someone tell me why?

+4
source share
3 answers

As you can see, non-interconnected interfaces are all-inclusive and eating, but at the same time, both Line 1 and Line 2 print "Food Instances" and "Instances explicitly" respectively.

Can someone tell me why?

Since the object you are testing is ursus , which implements omnivora and also implements eat (inheriting from mammalia ).

One of the key features of interfaces is that a class can implement several unrelated interfaces, and its instances are considered โ€œinstancesโ€ of each of these interfaces.

A specific example would be FileReader , which extends Reader , but also implements Readable , Closeable and AutoCloseable . These last two are not related to reading, in fact, but class instances are instances of all these interfaces.

+4
source

Mammalia implements both eat and omnivora , which means that any of the Mammalia subclasses is a subtype of both of these interfaces. Thus, any ursus object is both eat and omnivora .

+1
source

The instanceof operator does not check the type of a static object, but a dynamic type. (omnivora)i instanceof eat exactly matches i instanceof eat .

No matter how much you use it, the dynamic type i is equal to ursus , which is a subclass of eat and omnivora . The result cannot be different from what you get.

Please abide by the Java naming conventions. Your program is extremely difficult to read.

+1
source

Source: https://habr.com/ru/post/1498807/


All Articles