公司要招人,我帮经理准备了一道面试题,考Java基础的

编程题很简单,三个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群里小问了一下,实在惭愧。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值