java - Understanding polymorphism with multiple classes and an interface form of instantiation -
interface shape { public double area(); } class circle implements shape { private double radius; public circle(double r){radius = r;} public double area(){return math.pi*radius*radius;} } class square implements shape { private int wid; public square(int w){wid = w;} public double area(){return wid *wid;} } public class poly{ public static void main(string args[]){ shape[] s = new shape[2]; s[0] = new circle(10); s[1] = new square(10); system.out.println(s[0].getclass().getname()); system.out.println(s[1].getclass().getname()); } }
in effort understand concept of polymorphism, found following post (https://stackoverflow.com/a/4605772/112500) noticed charlie created shape class unimplemented method.
as 1 can see code, converted class interface , used instantiate anonymous class called appropriate method.
could tell me if solution sound? have written code in different manner? why use of interface on both sides of equal sign function does?
thanks.
caitlin
that looks fine me - though you're not using anonymous classes anywhere, show how basic polymorphism works.
in general, in code like
shape s1 = new circle(2); shape s2 = new square(2);
both lines above work because circle
, square
implement shape, saying 'circle shape' , 'square shape'. declaring 's1' being type shape
saying can refer is-a shape
, ie. implements shape
. note can only call methods defined in shape
interface through s1
, s2
. circle had method diameter
then:
shape s1 = new circle(2); s1.diameter();
will fail, because diameter
doesn't exist on shape
interface: type variable declared defines methods can seen, not actual class of instance variable refers to. implementation called is determined actual class of instance referred - core of polymorphism.
Comments
Post a Comment