Bài 1 Cirlce và Cylinder
Chúng ta có class Cylinder thừa kế class Circle.
Constructor Cylinder(radius: double, color: String, height: double): Trong đó height sẽ được gán cho biến heigth của class Cylinder. Sử dụng super để gọi constructor của class cha.
getVolume(): = getArea() * heigth
// File Circle.java
public class Circle {
private double radius;
private String color;
public Circle(double radius, String color) {
this.radius = radius;
this.color = color;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getArea() {
return this.radius * this.radius * Math.PI;
}
public String toString() {
return "Circle{" +
"radius=" + radius +
", color='" + color + '\'' +
'}';
}
}
// File Cylinder.java
public class Cylinder extends Circle {
private double heigth;
public Cylinder(double radius, String color, double heigth) {
super(radius, color);
this.heigth = heigth;
}
public double getHeigth() {
return heigth;
}
public void setHeigth(double heigth) {
this.heigth = heigth;
}
public double getVolumer() {
return super.getArea() * this.heigth;
}
}
// File Main.java
public class Main {
public static void main(String[] args) {
Circle cylinder = new Cylinder(2.4, "red", 10);
System.out.println("Area: " + cylinder.getArea());
System.out.println("Volume: " + ((Cylinder) cylinder).getVolumer());
}
}
Output:
Area: 18.09557368467721
Volume: 180.95573684677208
Bài 2: Person, Student và Staff
Ở ví dụ này, chúng ta có class cha Person được class Student và Staff thừa kế. Hãy triển khai chương trình như sơ đồ trên/
upToSalary(int percent): salary + (salary * percent) / 100
getRating(): score < 5 => bad; score >= 5 và score < 8 => medium, score >= 8 => good

