Skip to content

Instantly share code, notes, and snippets.

@axsddlr
Last active May 18, 2018 17:16
Show Gist options
  • Save axsddlr/87533704a799d5bab0248ec1feb995a7 to your computer and use it in GitHub Desktop.
Save axsddlr/87533704a799d5bab0248ec1feb995a7 to your computer and use it in GitHub Desktop.
Project 2 created by Ayysir - https://repl.it/@Ayysir/Project-2
//Circle class inherited from the shape
//class with implementation to the methods.
public class Circle extends Shape {
private int radius;
public Circle(int radius) {
this.radius = radius;
}
@Override
public void calculateArea() {
double area = Math.PI * (this.radius * this.radius);
System.out.println("Circle Area is : " + area);
}
@Override
public void display() {
System.out.println("Created Circle - radius : " + radius);
}
}
//Rectangle class inherited from shape with
//implementation to the methods.
public class Rectangle extends Shape {
private int length;
private int breadth;
public Rectangle(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
@Override
public void calculateArea() {
int area = this.length * this.breadth;
System.out.println("Rectange Area is : "+ area);
}
@Override
public void display() {
System.out.println(" Created Rectangle - Length : "+ length + " Breadth : "+ breadth);
}
}
//abstract class with unimplemented abstract methods.
interface Shape
{
public double calculateArea();
}
ShapeDriver.java
public class ShapeDriver {
public static void main(String args[]){
//creating a rectangle with length 10 and bredth 20
Shape rectangle = new Rectangle(10,20);
rectangle.display();
rectangle.calculateArea();
//creating a circle with radius 5.
Shape circle = new Circle(5);
circle.display();
circle.calculateArea();
Shape triangle = new Triangle(3,5,7);
triangle.calculateArea();
}
}
public class Triangle extends Shape {
private final double a, b, c; // sides
public Triangle() {
this(1,1,1);
}
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public double calculateArea() {
// Heron's formula:
// A = SquareRoot(s * (s - a) * (s - b) * (s - c))
// where s = (a + b + c) / 2, or 1/2 of the perimeter of the triangle
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
@Override
public void display() {
System.out.println(" Created Triangle - Length : "+ length + " Breadth : "+ breadth);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment