Java的多态与继承

1、设计一个父类,图形类Shapes,代码如下:

abstract class Shapes
{
	protected double circumference;//周长
	protected double area;//面积

    abstract void setCircumference();
    abstract void setArea();

    public double getCircumference()
    {
		return circumference;
	}
	public double getArea()
	{
		return area;
	}
}

2、设计一个子类

class Rectangle extends Shapes
{
	protected int height;
	protected int width;

	Rectangle(int h,int w)
	{
		height=h;
		width=w;
	}
	public void setCircumference()
	{
		circumference=2*(height+width);
	}
	public void setArea()
	{
		area=height*width;
	}
}

3、编写一个测试类,测试子类能否正常运行

public class TestRectangle
{
	public static void main(String arg[])
	{
		Rectangle r1=new Rectangle(9,10);
		Rectangle r2=new Rectangle(2,8);
		r1.setCircumference();
		r2.setArea();
		System.out.println(r1.getCircumference());
		System.out.println(r2.getArea());
	}
}

4、编写一个实例来说明super(属性的隐藏与方法的继承),其中包涵了一个测试

class Box extends Rectangle  //继承与Rectangle的子类:矩形框类
{
	private int width;//内部正方框的边长,将隐藏父类同名属性
	Box(int h,int w)
	{
		super(h,w);
	}
	Box(int h,int w,int innerw)
	{
		this(h,w);
		width=innerw;
	}
	public void setWidth(int innerw)
	{
		width=innerw;
	}
	public int getWidth()
	{
		return width;
	}
	public void setCircumference()
	{
		super.setCircumference();

		circumference+=4*width;
	}
	public int setArea(int innerw)
	{
		return width*width;
	}
	public void setArea()
	{
		area=height*super.width-setArea(width);
	}
	public static void main(String args[])
	{
		System.out.println("Box类的操作情况如下:");
		Box b=new Box(10,8,2);
		b.setCircumference();
		b.setArea();
		System.out.println("框形:周长="+b.getCircumference()+"面积="+b.getArea());
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值