编程题很简单,三个class
1. Shape类
2. 继承Shape类的Rectangle类,编写计算面积和周长的方法
3. Test类,构造Rectangle类,运行程序,输出Rectangle类的面积和周长
代码如下:
class Shape{
protected int width;
protected int height;
protected int area; // 面积
protected int perimeter; // 周长
Shape() {}
Shape(int w, int h){
width = w;
height = h;
}
}
class Rectangle extends Shape{
protected int getPerimeter(){
perimeter = width * 2 + height *2;
return perimeter;
}
protected int getArea() {
area = width * height;
return area;
}
public Rectangle(int w, int h) {
super(w, h);
}
}
public class Test {
public static void main (String[] args){
Rectangle r = new Rectangle(8,6);
System.out.println("面积为:" + r.getArea());
System.out.println("周长为:" + r.getPerimeter());
}
}
后话:小弟做JSP做了2年了,大的项目没做过,但小的东西做了很多。感觉自己的Java基础太差了,得努力了。上面的code红色的部分居然被我忘记了,子类默认是调用父类的无参构造方法,所以得到的结果是,width=0,height=0,super(w,h)语句手动设置要执行的构造方法。我还到的QQ群里小问了一下,实在惭愧。