Java实验一 类的设计与对象使用

这篇博客探讨了Java中的类设计与对象使用,详细介绍了四种不同的实现方式,并展示了具体的运行结果,帮助读者理解Java编程中的核心概念。
摘要由CSDN通过智能技术生成

问题描述:编写一个程序计算梯形和圆形的面积

package ex1;

import java.util.Scanner;

class Circle{
   
	private double radius = 0;
	
	public Circle() {
   
		
	}
	
	public Circle(double radius) {
   
		this.radius = radius;
	}
	
	public double getArea() {
   
		return radius*radius*Math.PI;
	}
}


class Trapezoid{
   
	private double length1 = 0;
	private double length2 = 0;
	private double high = 0;
	
	public Trapezoid() {
   
		
	}
	
	public Trapezoid(double length1, double length2, double high){
   
		this.length1 = length1;
		this.length2 = length2;
		this.high = high;
	}
	
	public double getArea() {
   
		return (length1+length2)*high/2;
	}
}

public class Test {
   

	public static void main(String[] args) {
   
		Scanner stdIn = new Scanner(System.in);
		
		System.out.println("-----Class Circle Test-----");
		System.out.println("Please input the radius:");
		double radius = stdIn.nextDouble();
		Circle[] circleTest = new Circle[2];
		circleTest[0] = new Circle();
		circleTest[1] = new Circle(radius);
		System.out.println("The area of the circle1 is: " + circleTest[0].getArea());
		System.out.println("The area of the circle2 is: " + circleTest[1].getArea());
		
		System.out.println("-----Class Trapezoid Test-----");
		System.out.println("Please input the length1, length2, high in order:");
		double[] a = new double[3];
		for(int i=0; i<a.length; i++) {
   
			a[i] = stdIn.nextDouble();
		}
		Trapezoid trapezoidTest = new Trapezoid(a[0], a[1], a[2]);
		System.out.printf("The area of the Trapezozid is: %.2f", trapezoidTest.getArea());

	}

}

运行结果
image


更新
四种实现方式
1.

package ex1;	//第一次试验

import java.util.Scanner;


//继承实现

//抽象类Shape
abstract class Shape{
   
	abstract public double getArea();
}

//Circle继承Shape
class Circle extends Shape{
   
	private double radius = 
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值