java - Using instanceof to test interfaces -


i've been having bit of trouble problem. question:

write complete java program following:

  • declares interfaces i1 , i2, both empty bodies
  • declare interface i3 empty body, extends both of above interfaces
  • declare interface i4 empty body
  • class x implements i3 empty body
  • class w empty body implements i4 , extends x
  • create class instanceoftest following in main():
    • create object w of class w.
    • use instanceof operator test if object w implements each of interfaces , of type x, , display appropriate message.

so i've come far:


public interface i1 {  } 

public interface i2 {  } 

public interface i3 extends i1, i2 {  } 

public interface i4 {  } 

public class w extends x implements i4 {  } 

i'm having bit of confusion instanceoftest method. know instanceof operator tell if object instance of type, when this:


public class instanceoftest {      public static void main(string[] args)     {         w w = new w();         if (w instanceof x)         {             system.out.println("w instance of x.");         }     } } 

the problem i'm having using instanceof see if w implements each of interfaces. have no idea how go doing that. appreciated!


edit: so, should this?


public class instanceoftest {     public static void main(string[] args)     {         w w = new w();         if (w instanceof x)         {             system.out.println("w instance of x.");         }          if (w instanceof i1)         {             system.out.println("w implements i1.");         }          if (w instanceof i2)         {             system.out.println("w implements i2.");         }          if (w instanceof i3)         {             system.out.println("w implements i3.");         }          if (w instanceof i4)         {             system.out.println("w implements i4.");         }     } } 

well, here full solution you:

public interface i1 {} 

public interface i2 {} 

public interface i3 extends i1, i2 {} 

public interface i4 {} 

public class x implements i3 {} 

public class w extends x implements i4 {} 

public class instanceoftest {   public static void main(string[] args){       w w = new w();        if (w instanceof i1)         system.out.println("w implements i1");        if (w instanceof i2)         system.out.println("w implements i2");        if (w instanceof i3)         system.out.println("w implements i3");        if (w instanceof i4)         system.out.println("w implements i4");        if (w instanceof x)         system.out.println("w extends x");     } } 

and result w implements every interface , extends x.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -