Java:实现抽象类形状,并派生出三角形,圆,矩形类

import java.util.Scanner;
public class Shape {
	public static void main(String[]args) {
		Shape s=new Shape();
		Scanner sc=new Scanner(System.in);
		System.out.println("输入随机生成图形个数:");
		int N=sc.nextInt();
		shape ss[]=new shape[N+1];
		for(int i=0;i<N;i++){
			System.out.println("输入图形:\n1:三角形\n2:圆形\n3:矩形");
			int j=sc.nextInt();
			switch(j) {
			case 1:
				{
					int a,b,c;
					do {
					System.out.print("输入三角形三边:");
					a=sc.nextInt();
					b=sc.nextInt();
					c=sc.nextInt();
					if(a+b<=c||a+c<=b||b+c<=a) {
						System.out.println("数据不合法,请重新输入!");
					}
					else break;
					}while(true);
					ss[i]=s.new Triangle(a,b,c);
					break;
				}
				case 2:
				{
				System.out.print("输入圆的半径:");
				int rr;
				rr=sc.nextInt();
				ss[i]=s.new Circle(rr);
				break;
				}
			case 3:
				{
				System.out.print("输入矩形长和宽:");
				int a,b;
				a=sc.nextInt();
				b=sc.nextInt();
				ss[i]=s.new Rectangle(a,b);
				break;
				}
			}
		}
		for(int i=0;i<N;i++) {
			ss[i].Getsqual();
			ss[i].Showsqual();
		}
		sc.close();
		return;
	}
	public abstract class shape{
		abstract void Getsqual();
		public abstract void Showsqual();
	}
	public class Triangle extends shape{
		double squal;
		int l1,l2,l3;
		
		public Triangle(int l1, int l2, int l3) {
			super();
			this.l1 = l1;
			this.l2 = l2;
			this.l3 = l3;
		}

		@Override
		void Getsqual() {
			double p=(l1+l2+l3)/2.0;
			squal=Math.sqrt(p*(p-l1)*(p-l2)*(p-l3));
		}

		@Override
		public void Showsqual() {
			System.out.println("Triangle squal:"+squal);
		}
	}
	public class Circle extends shape{
		double squal;
		int r;
		
		public Circle(int r) {
			super();
			this.r = r;
		}

		@Override
		void Getsqual() {
			double PI=3.14159;
			squal=PI*r*r;
		}

		@Override
		public void Showsqual() {
			System.out.println("Circle squal:"+squal);
		}
	}
	public class Rectangle extends shape{
		double squal;
		int length,width;
		
		public Rectangle(int length, int width) {
			super();
			this.length = length;
			this.width = width;
		}

		@Override
		void Getsqual() {
			squal=length*width;
		}

		@Override
		public void Showsqual() {
			System.out.println("Rectangle squal:"+squal);
		}
		
	}
}

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

淬炼之火

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值