Diksha Diksha - 1 year ago 68
Java Question

Java: Abstract classes methods and interface

The program below calculates the total of the areas of any number of shapes instantiated. The problem is that I don't know how to output the draw() method of the interface.

Here is the main class:

public class MyClass1{

public static void main(String[] args) {

Shape[] shapes= new Shape[3];

shapes[0]= new Circle(20.0);
shapes[1]= new Rectangle(25, 63);
shapes[2]= new Circle(25);

double total=0;

for(int i=0; i<shapes.length; i++){

total+= shapes[i].area();


System.out.printf("Total: %.1f", total);



The superclass Shape

abstract class Shape {

abstract double area();


The interface Drawable

public interface Drawable {
public abstract void draw();


The subclass Circle

public class Circle extends Shape implements Drawable {

double radius;

Circle(double aRadius){

radius= aRadius;

double area(){

return Math.PI*radius*radius;

public void draw(){
System.out.println("This is a circle");


The subclass Rectangle

public class Rectangle extends Shape implements Drawable {

double width, height;

public Rectangle(double aWidth, double aHeight){

width= aWidth;
height= aHeight;


double area(){

return width*height;

public void draw(){

System.out.println("This is a rectangle.");

I assumed that to print out the draw() method,the code should be like this:

Shape obj= new Rectangle();
Shape obj1= new Circle();


But it's not working out. Would like to know the correct way to print the draw method along with some explanation since I am a newbie in Java.

Answer Source

The draw method is not available, because you have Shapes in your array, not Drawables. You could theoretically have UndrawableShape that extends Shape but doesn't implement Drawable, so the compiler won't let you call a draw() method that may not exist.

To call draw(), you can do the following:

Instead of having each concrete subclass implement Drawable, have the Shape class implement Drawable. Shape is abstract, so it doesn't have to implement draw() itself; subclasses will need to implement that method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download