过载子类构造函数java

时间:2014-03-15 13:40:46

标签: java constructor-overloading

是否有可能重载子类的构造函数,因为我一直绞尽脑汁而且我真的无法理解它。下面是我到目前为止的整个代码和问题。

这是学校的工作,但由于我们在几周内完成了概念考试,所以没有评分,所以我试图通过尽可能多的练习。

练习4 - 重载构造函数

我们注意到大多数计算机实验室的容量都是20。

为ComputerLab类编写一个新的构造函数,它只有一个参数,房间号,并将容量初始化为20.我们现在已经重载了ComputerLab类的构造函数,因此有两种方法可以创建实例上课。

Week7.java:

package week7;


public class Week7 {
    /*
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        Room nonTech = new Room("t12", 25, true);
        System.out.println("nonTech");
        System.out.println(nonTech.getRoomNumber());
        System.out.println(nonTech.getCapacity());
        System.out.println(nonTech.hasProjector());

        ComputerLab tech = new ComputerLab("r12", 10, true, "win7");
        System.out.println();
        System.out.println("tech");
        System.out.println(tech.getRoomNumber());
        System.out.println(tech.getCapacity());
        System.out.println(tech.hasProjector());
        System.out.println(tech.getOS());

        // hasProjector == false however it will also return true due 
        //to the override method lower down
        LectureRoom mainhall = new LectureRoom("somthing", 100, false);
        System.out.println();
        System.out.println("mainhall");
        System.out.println(tech.hasProjector());

    }
}

class Room {

    String roomNumber;
    int capacity;
    boolean projection;

    public Room(String rm, int n, boolean p) {
        roomNumber = rm;
        capacity = n;
        projection = p;
    }

    public String getRoomNumber() {
        return roomNumber;
    }

    public int getCapacity() {
        return capacity;
    }

    public boolean hasProjector() {
        return projection;
    }
}

class ComputerLab extends Room {
    // RoomNumber, capacity, projection inherited

    private String os;

    public ComputerLab(String rm, int n, boolean p, String os) {
        super(rm, n, p);
        this.os = os;
    }

    public String getOS() {
        return os;
    }

    public void setOS(String update) {
        os = update;
    }

}

class LectureRoom extends Room {
    // RoomNumber, capacity, projection inherited

    public LectureRoom(String rm, int n, boolean p) {
        super(rm, n, p);
    }

    // Overrides Superclass hasProjector
    public boolean hasProjector() {
        return true;
    }
}

1 个答案:

答案 0 :(得分:0)

您需要为ComputerLab类添加一个构造函数,将capacity设置为20:

public ComputerLab(String roomNumber) {
    super(roomNumber, 20, false); // is false the correct default value?
    this.os = null; // what is the correct default value?
}

super这里调用超类构造函数(在这种情况下为Room),因此您将所需的参数传递给它。在此特定情况下,您的ComputerLab实例为Room,其房间号为roomNumber(新ComputerLab构造函数的参数),容量设置为{{1} }并将投影设置为20