Skip to content

Instantly share code, notes, and snippets.

@Vishal1297
Last active August 6, 2020 18:19
Show Gist options
  • Save Vishal1297/8adec043aa2f3de49fa214f6a085ecee to your computer and use it in GitHub Desktop.
Save Vishal1297/8adec043aa2f3de49fa214f6a085ecee to your computer and use it in GitHub Desktop.
A Java Abstraction Example.
import java.util.Scanner;
public class AbstractionExample {
public static void main(final String[] args) {
Scanner scanner = new Scanner(System.in);
Shape shape = null;
System.out.println("AREA OF SHAPE");
System.out.println("1. Rectange\n2. Square");
System.out.print("Choice ? ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
shape = new Rectangle();
System.out.print("Height Of Rectangle :: ");
int height = scanner.nextInt();
System.out.print("Width Of Rectangle :: ");
int width = scanner.nextInt();
shape.setHeight(height);
shape.setWidth(width);
System.out.print("Area Of Rectangle :: ");
break;
case 2:
Square square = new Square();
System.out.print("Side Of Square :: ");
square.setSide(scanner.nextInt());
shape = square;
System.out.print("Area Of Square :: ");
break;
default:
break;
}
System.out.println(shape.getArea());
scanner.close();
}
}
abstract class Shape {
private int height = 0;
private int width = 0;
public int getHeight() {
return height;
}
public void setHeight(final int height) {
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(final int width) {
this.width = width;
}
public abstract long getArea();
}
class Rectangle extends Shape{
@Override
public long getArea() {
return getHeight()*getWidth();
}
}
class Square extends Shape {
private int side = 0;
@Override
public long getArea() {
return getSide()*getSide();
}
public int getSide() {
return side;
}
public void setSide(int side) {
this.side = side;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment