【水汐のjava】设计抽象形状类Shape,包含输出周长的方法;重写输出周长的方法。在主函数中创建圆类(Circle)和长方形类(Rectangle)

本文介绍了一种使用抽象类设计形状类的方法,包括圆类(Circle)和长方形类(Rectangle)。通过继承抽象形状类Shape,子类重写了打印名称和计算面积的方法。在主函数中,创建了多个形状对象并利用多态性输出其周长。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

非抽象类的实现方法

package hiwari;
/*
 * 设计抽象形状类Shape,包含输出周长的方法;
 * 重写输出周长的方法。在主函数中创建圆类(Circle)和长方形类(Rectangle),
 * 重写输出周长的方法。在主函数中创建圆类和长方形类对象各3个,
 * 将这些对象转换成Shape类型后,用for循环输出各个对象的周长
 * */

    class Shape {
	void printName(){
		System.out.println("未知形状");
	}
	void area()
	{
		System.out.println("未知面积");
	}	
	}
	class Circle extends Shape
	{
		double r;
		void printName()
		{
			System.out.println("圆形");
		}
		void area()
		{
			System.out.println(3.14*r*r);
		}
		Circle(double a){r=a;}
	}
	class Rectangle extends Shape
	{
		double l,h;
		
		void printName()
		{
			System.out.println("长方形");
		}
		void area()
		{
			System.out.println(l*h);
		}
		Rectangle(double a,double b){l=a;h=b;}
	}


public class text {

	public static void  main(String[] args) {
			Shape s[]=new Shape[2];
			s[0]=new Circle(2);
			s[1]=new Rectangle(2,3);
			for(int i=0;i<2;i++)
			{
				s[i].printName();
				s[i].area();
			}
}
}

抽象类的实现方法

package hiwari;
/*
 * 设计抽象形状类Shape,包含输出周长的方法;
 * 重写输出周长的方法。在主函数中创建圆类(Circle)和长方形类(Rectangle),
 * 重写输出周长的方法。在主函数中创建圆类和长方形类对象各3个,
 * 将这些对象转换成Shape类型后,用for循环输出各个对象的周长
 * */

    abstract class Shape {
    	abstract void printName();
    	abstract void area();
	}
	class Circle extends Shape
	{
		double r;
		void printName()
		{
			System.out.println("圆形");
		}
		void area()
		{
			System.out.println(3.14*r*r);
		}
		Circle(double a){r=a;}
	}
	class Rectangle extends Shape
	{
		double l,h;
		
		void printName()
		{
			System.out.println("长方形");
		}
		void area()
		{
			System.out.println(l*h);
		}
		Rectangle(double a,double b){l=a;h=b;}
	}


public class text {

	public static void  main(String[] args) {
			Shape s[]=new Shape[2];
			s[0]=new Circle(2);
			s[1]=new Rectangle(2,3);
			for(int i=0;i<2;i++)
			{
				s[i].printName();
				s[i].area();
			}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值