Java program on abstraction, shapes example

ABSTRACTION:

Abstraction is a process of hiding the implementation details and showing only functionality to the user. 
There are two ways to achieve abstraction in java:
  1. Abstract class (0 to 100%)
  2. Interface (100%)
A class that is declared using “abstract” keyword is known as abstract class. It can have abstract methods(methods without body) as well as concrete methods (regular methods with body). A normal class(non-abstract class) cannot have abstract methods.

PROGRAM:

import java.util.Scanner;

abstract class Shape {
    float area;

    abstract void input();

    abstract void calArea();

    void disp() {
        System.out.println("Area= " + area);
    }
}

class Square extends Shape {
    float l;
    private Scanner s = new Scanner(System.in);

    void input() {
        System.out.println("Enter length");
        l = s.nextFloat();
    }

    void calArea() {
        area = l * l;
    }
}

class Rectangle extends Shape {
    float l, b;
    private Scanner s = new Scanner(System.in);

    void input() {
        System.out.println("Enter length and breadth");
        l = s.nextFloat();
        b = s.nextFloat();
    }

    void calArea() {
        area = l * b;
    }
}

class Circle extends Shape {
    float r;
    final float PI = 3.1416f;
    private Scanner s = new Scanner(System.in);

    void input() {
        System.out.println("Enter radius");
        r = s.nextFloat();
    }

    void calArea() {
        area = PI * r * r;
    }
}

class Geometry {
    void createShape(Shape ref) {
        ref.input();
        ref.calArea();
        ref.disp();
    }
}

public class ShapesApp {
    public static void main(String... args) {
        Square s = new Square();
        Rectangle r = new Rectangle();
        Circle c = new Circle();
        Geometry g = new Geometry();
        g.createShape(s);
        g.createShape(r);
        g.createShape(c);
    }

}

OUTPUT:

Enter length
10
Area= 100.0
Enter length and breadth
10 20
Area= 200.0
Enter radius
10
Area= 314.15997

Popular Posts