By GokiSoft.com|
18:49 22/04/2024|
Java Basic
[Share Code] Bài tập kế thừa hình tròn + hình chữ nhật - lập trình Java căn bản - Đề 2 - C2307L
Bài tập kế thừa hình tròn + hình chữ nhật - lập trình Java căn bản - Đề 2
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package lesson06;
/**
*
* @author diepvan
*/
public class Main {
public static void main(String[] args) {
HinhChuNhat hcn = new HinhChuNhat(22f, 17f);
HinhTron ht = new HinhTron(22.7f);
//Cach 1
double dt = hcn.tinhDienTich() + ht.tinhDienTich();
System.out.println("Tong dien tich: " + dt);
//Cach 2
Shape[] list = new Shape[2];
list[0] = hcn;
list[1] = ht;
dt = tinhTongDienTich(list);
System.out.println("Tong dien tich: " + dt);
}
public static double tinhTongDienTich(Shape[] list) {
double dt = 0;
for (Shape shape : list) {
dt += shape.tinhDienTich();
}
return dt;
}
public static class Shape {
public Shape() {
}
public double tinhChuVi() {
return 0;
}
public double tinhDienTich() {
return 0;
}
}
public static class HinhTron extends Shape {
double radius;
public HinhTron() {
}
public HinhTron(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
@Override
public double tinhDienTich() {
return Math.PI * radius * radius;
}
@Override
public double tinhChuVi() {
return 2 * Math.PI * radius;
}
}
public static class HinhChuNhat extends Shape {
double width;
double height;
public HinhChuNhat() {
}
public HinhChuNhat(double width, double height) {
this.width = width;
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
@Override
public double tinhChuVi() {
return 2 * (width + height);
}
@Override
public double tinhDienTich() {
return width * height;
}
}
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)