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());
}
}