Created
June 8, 2021 03:01
-
-
Save trhgquan/bb880e756453d2696a51c16e135231bf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package _3; | |
import java.util.*; | |
public class Test { | |
public static void main(String[] args) { | |
Shape s = new Rectangle(3, 4, "white"); | |
System.out.println(s.toString()); | |
System.out.println("Area = " + s.getArea()); | |
s = new Triangle(4, 5, "black"); | |
System.out.println(s.toString()); | |
System.out.println("Area = " + s.getArea()); | |
} | |
} | |
public abstract class Shape { | |
protected String color; | |
// | |
// Constructor | |
// | |
public Shape() { | |
this.color = ""; | |
} | |
public Shape(String color) { | |
this.color = color; | |
} | |
public abstract double getArea(); | |
// | |
// Getter & setter | |
// | |
public String getColor() { | |
return this.color; | |
} | |
public void setColor(String color) { | |
this.color = color; | |
} | |
} | |
public class Rectangle extends Shape { | |
private double length; | |
private double width; | |
public Rectangle() { | |
super(); | |
this.length = 0; | |
this.width = 0; | |
} | |
public Rectangle(double length, double width, String color) { | |
this.length = length; | |
this.width = width; | |
super(color); | |
} | |
@Override | |
public double getArea() { | |
return this.length * this.width; | |
} | |
public double getPerimeter() { | |
return 2.0 * (this.length + this.width); | |
} | |
public String toString() { | |
return "Rectangle{length=" + length + | |
", width=" + width + | |
", color=" + color + "}"; | |
} | |
} | |
public class Triangle extends Shape { | |
private double base; | |
private double height; | |
public Triangle() { | |
super(); | |
this.base = 0; | |
this.height = 0; | |
} | |
public Triangle(double base, double height, String color) { | |
super(color); | |
this.base = base; | |
this.height = height; | |
} | |
public double getArea() { | |
return 0.5 * this.base * this.height; | |
} | |
public String toString() { | |
return "Triangle{base=" + base + | |
", height=" + height + | |
", color=" + color + "}"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment