1.以下兩者皆出錯,請問是因為物件不能在main()之外建立是嗎? 建立物件是main()內才可以執行的動作嗎?
2.color和milesDriven就可以在main()外建立好,但為何Car myFastCar = new Car();必須寫在main()中?
public class Car {
String color ="yello";
int milesDriven = 23;
Car myFastCar = new Car(); //錯誤
public static void main(String[] args){
System.out.println(myFastCar.color);
System.out.println(myFastCar.milesDriven);
}
3.為何在main()中才建立物件,仍會錯誤?
public class Car {
String color ="yello";
int milesDriven = 23;
Car myFastCar; //出現錯誤
public static void main(String[] args){
myFastCar = new Car();
System.out.println(myFastCar.color);
System.out.println(myFastCar.milesDriven);
}
}
4.以下兩者有什麼不同? 第一個將物件建立在constructor中,第二個在field中。
public class Car {
Bike bike;
Car(){
bike = new Bike(); //在contructor中建立
bike.color("red");
}
public static void main(String[] args) {
Car car = new Car();
}
}
class Bike {
void color(String c) {
System.out.println(c);
}
}
public class Car {
Bike bike = new Bike(); //在field中建立
Car(){
bike.color("red");
}
public static void main(String[] args) {
Car car = new Car();
}
}
class Bike {
void color(String c) {
System.out.println(c);
}
}