w3resource

Java: Abstract Shape2D Class with Rectangle and Circle Subclasses

Java Abstract Class: Exercise-10 with Solution

Write a Java program to create an abstract class Shape2D with abstract methods draw() and resize(). Create subclasses Rectangle and Circle that extend the Shape2D class and implement the respective methods to draw and resize each shape.

Sample Solution:

Java Code:

//Shape2D.java
abstract class Shape2D {
  public abstract void draw();

  public abstract void resize();
}

//Rectangle.java
class Rectangle extends Shape2D {
  @Override
  public void draw() {
    System.out.println("Rectangle: Drawing a rectangle.");
  }

  @Override
  public void resize() {
    System.out.println("Rectangle: Resizing the rectangle.");
  }
}
//Circle.java
class Circle extends Shape2D {
  @Override
  public void draw() {
    System.out.println("Circle: Drawing a circle.");
  }

  @Override
  public void resize() {
    System.out.println("Circle: Resizing the circle.");
  }
}
//Main.java
public class Main {
  public static void main(String[] args) {
    Shape2D rectangle = new Rectangle();
    Shape2D circle = new Circle();

    rectangle.draw();
    rectangle.resize();

    circle.draw();
    circle.resize();
  }
}

Sample Output:

Rectangle: Drawing a rectangle.
Rectangle: Resizing the rectangle.
Circle: Drawing a circle.
Circle: Resizing the circle.

Explanation:

In the above exercise -

  • The abstract class "Shape2D" has two abstract methods: draw() and resize(). The subclasses Rectangle and Circle extend the Shape2D class and provide their own implementations for these abstract methods.
  • The "Rectangle" class describes how to draw and resize a rectangle, while the "Circle" class describes how to draw and resize a circle.
  • In the main method, we create instances of Rectangle and Circle, and then call the draw() and resize() methods on each object to demonstrate how each shape is drawn and resized.

Flowchart:

Flowchart: Person Java
Flowchart: Athlete Java
Flowchart: LazyPerson Java
Flowchart: Main Java

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Abstract Instrument Class with Glockenspiel and Violin Subclasses.
Next: Abstract Bird Class with Eagle and Hawk Subclasses.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.