Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding polymorphism with multiple classes and an interface form of instantiation

Tags:

java

oop

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 an effort to understand the concept of polymorphism, I found the following post (https://stackoverflow.com/a/4605772/112500) but I noticed that Charlie created the Shape class with a unimplemented method.

As one can see from my code, I converted that class into an interface and then used it to instantiate an anonymous class which then called the appropriate method.

Could someone tell me if my solution is sound? Would you have written the code in a different manner? Why does the use of an interface on both sides of the equal sign function as it does?

Thanks.

Caitlin

like image 829
CaitlinG Avatar asked Jul 18 '13 09:07

CaitlinG


1 Answers

An anonymous class in Java is a class not given a name and is both declared and instantiated in a single statement. You should consider using an anonymous class whenever you need to create a class that will be instantiated only once.

An anonymous class must always implement an interface or extend an abstract class. However, you don’t use the extends or implements keyword to create an anonymous class. Instead, you use the following syntax to declare and instantiate an anonymous class:

new interface-or-class-name() { class-body } 

One example would be :

Shape s = new Shape() // no square brackets here
{
    public double area()
    {
        return 10.0;
    }
};

No where in your posted code you are creating any anonymous class.

Read the Oracle tutorial and this for more.


When you do this :

Shape[] s = new Shape[2] // notice the square brackets : "[2]"

You are actually creating an array which can have references to objects of Shape and its subtypes. So , this array can contain reference to objects of any class which implements Shape :

s[0] = new Circle();
s[1] = new Square();
like image 195
AllTooSir Avatar answered Sep 24 '22 05:09

AllTooSir