[英]overload subclass constructor java
是否可以重載子類的構造函數,因為我一直在絞盡腦汁,但我真的不知道。 下面是到目前為止的全部代碼和問題。
這是學校的工作,但由於我們在幾周內進行概念考試而未給其評分,因此我正在嘗試通過盡可能多的練習。
練習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;
}
}
您需要為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
構造函數的參數),容量設置為20
,投影設置為false
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.