好吧,直到現在(因爲我是一個初學者)我是基於程序設計編程Java,它很好,所有,但現在是時候使用Java像一個老闆。在Java中的OOP - 創建對象
我正在學習OOP概念,現在寫一些代碼作爲練習。 我不明白的是,如果我創建了幾個對象是這樣的:
Contact first = new Contact(25, "Yosi", "Male");
System.out.println("Age of contact " + first.toString() + " is - "
+ first.getAge() + " " + first.getName());
Contact second = new Contact(22, "lisa", "Femal");
System.out.println("Age of contact " + second.toString() + " is - "
+ second.getAge() + " " + second.getName());
Contact third = new Contact(34, "Adam", "Male");
System.out.println("Age of contact " + third.toString() + " is - "
+ third.getAge() + " " + third.getName());
結果將是:
Age of contact [email protected] is - 25 Yosi
Age of contact [email protected] is - 22 lisa
Age of contact [email protected] is - 34 Adam
但是,如果我再嘗試再次打印第一次接觸,它會得到創建的最後一個對象的值。我的意思是,對於這個代碼:
Contact first = new Contact(25, "Yosi", "Male");
System.out.println("Age of contact " + first.toString() + " is - "
+ first.getAge() + " " + first.getName());
Contact second = new Contact(22, "lisa", "Femal");
System.out.println("Age of contact " + second.toString() + " is - "
+ second.getAge() + " " + second.getName());
Contact third = new Contact(34, "Adam", "Male");
System.out.println("Age of contact " + third.toString() + " is - "
+ third.getAge() + " " + third.getName());
System.out.println("Age of contact " + first.toString() + " is - "
+ first.getAge() + " " + first.getName());
的結果將是:
Age of contact [email protected] is - 25 Yosi
Age of contact [email protected] is - 22 lisa
Age of contact [email protected] is - 34 Adam
Age of contact [email protected] is - 34 Adam
我已經添加了對象的字符串表示,所以你可以看到不同的對象。 我以爲我正在創建一個新的對象,每個對象都有它自己的實例值? 你們可以向我解釋一下嗎?
這是接觸類:
public class Contact {
private static int age = 0;
private static String name = "Unknown";
private static String gender = "Male";
public Contact(int a, String n, String g) {
age = a;
name = n;
gender = g;
}
public Contact() {
}
public static int getAge() {
return age;
}
public static String getName() {
return name;
}
public static String getGender() {
return gender;
}
public static void setAge(int a) {
age = a;
}
public static void setName(String n) {
name = n;
}
public static void setGender(String g) {
gender = g;
}
}
請注意,如果我刪除靜態預選賽我得到的錯誤說:「不能讓一個靜態的全球化志願服務青年的非靜態字段」
請發佈您的聯繫人類的代碼。最有可能的是,你有靜態屬性。 – alex