编程定义一个图形接口 Shape, 内含2个抽象方法 getArea()和toString().

2025-02-25 22:59:32
推荐回答(1个)
回答1:

楼主你好

具体代码如下:
/*Shap 接口*/
public interface Shap {
public int getArea();
public String toString();
}

/*Rectangle 抽象类*/
public abstract class Rectangle implements Shap{
public int width,length;

public Rectangle(int w,int l)
{
width = w;
length = l;
}

public Rectangle(){}

public int getArea()
{
return width*length;
}

public String toString()
{
return "长为:"+length+"\t宽为:"+width;
}

public abstract int getGirth();
}

/*Square具体类*/
public class Square extends Rectangle{

public Square(int l) {
super(l,l);
}

public int getGirth()
{
return 2*(width + length);
}
}

/*Test测试类*/
public class Test {
public static void main(String[] args) {
Square sq = new Square(5);//创建子类对象
Rectangle re = (Rectangle)new Square(3);//通过引用子类对象来创建父类对象

System.out.println (re+"\n面积为:"+re.getArea()+"\n");
System.out.println (sq+"\n面积为:"+sq.getArea()+"\t周长为:"+sq.getGirth());
}
}

运行结果:
长为:3 宽为:3
面积为:9
长为:5 宽为:5
面积为:25 周长为:20

希望能帮助你哈
(ps:不懂的 请继续追问)