java - Valid members of polymorphic array of an Interface type -


following sample class design hope me ask question:

public interface foo  {     int somemethod(); }  public abstract class bar implements foo  {     public int somemethod()     {        return 1;     } }  public class baz extends bar  {  }  public class quz extends bar  {     public int somemethod()     {        return 2;     } }  public class norf extends baz  {     public static void main(string[] args)      {         foo[] arr = new foo[4];          // code take advantage of polymorphism     } } 

in norf class , have created polymorphic array of type foo (which interface). trying understand objects of classes allowed member/element of array.

from understand , if making polymorphic array of class , objects created sub-class (any of descendant in inheritance tree) can member of array.

i trying formulate rule polymorphic array of interface.

coming sample class design , following seems valid (i typed out in ide , did not complain)

    arr[0] = new baz();     arr[1] = new quz();     arr[2] = new norf(); 

so looks objects of non abstract class implements interface or of it's concrete sub classes can member of array.

is there missing or can added above rule ?

expanding on @karthik's answer, instance implements foo can element of array. , class implements foo either directly or, indirectly, being descendant of class implements or being descendant of descendant of class implements it, etc etc.

or happen interface extends foo , class implements subinterface; valid instance of such class element of array:

public interface subfoo extends foo { }  public class blablab implements subfoo {      public int somemethod() {         return 3;     } } 

a few examples:

foo[] arr = new foo[7]; arr[0] = new baz(); arr[1] = new quz(); arr[2] = new norf(); arr[3] = () -> 7; // foo has 1 method, lambdas allowed arr[4] = new bar() {}; // anonymous classes allowed arr[5] = new subfoo() { public int somemethod() { return 123; } }; arr[6] = new blablab(); 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -