2015-04-03 170 views
1

嗨,這可能看起來像一個非常愚蠢的問題,但我最近進入了Java和我自己的構造函數。構造函數混淆Java

public class creatures { 
    private static String name; 
    private static int age; 
    private static String type; 

    public creatures(String name, int age, String type) { 
     this.name = name; 
     this.age = age; 
     this.type = type; 
     System.out.println("The creature's name is " + name + " \nThe creatures age is" + age + " \nThe creatures type is " + type); 
    } 

    public static void main(String [] args) { 
     creatures newcreature = new creatures("Zack", 100, "alien"); 
     creatures newcreature1 = new creatures("Jonny", 500, "vampire"); 
     creatures newcreature2 = new creatures("Dick", 4, "witch"); 
     System.out.println(newcreature.name); 
    } 
} 
在我的主要方法的System.out.println

因此,印刷在構造後,我想通過引用我newcreature構造函數的名稱,打印名稱爲「扎克」,但它只是打印名稱「迪克」來自我所做的最後一個構造函數。我如何區分這些在同一個類中的構造函數?如果這是一個愚蠢的問題,再次抱歉。

+2

爲什麼你所有的字段都是'靜態'?刪除。 – 2015-04-03 09:25:33

+0

工作感謝!哇,我覺得很愚蠢 – 2015-04-03 09:29:10

回答

0

因爲你的名字字段是靜態的,所以它共享一個共同的內存。所以如果你試圖用不同的對象來重新訪問它,它會給出相同的輸出。

由於您上次更改了值new creatures("Dick", 4, "witch");Dick它將更改爲它。

因此消除靜電關鍵字,以得到所需的O/P

public class creatures { 
    private String name; 
    private int age; 
    private String type; 

    public creatures(String name, int age, String type) { 
     this.name = name; 
     this.age = age; 
     this.type = type; 
     System.out.println("The creature's name is " + name + " \nThe creatures age is" + age + " \nThe creatures type is " + type); 
    } 

    public static void main(String [] args) { 
     creatures newcreature = new creatures("Zack", 100, "alien"); 
     creatures newcreature1 = new creatures("Jonny", 500, "vampire"); 
     creatures newcreature2 = new creatures("Dick", 4, "witch"); 
     System.out.println(newcreature.name); 
    } 
} 

輸出

Zack 
0

類的所有數據成員都是靜態的,這就是爲什麼每個實例共享相同的成員。當你創建生物的新實例時,構造函數只是用新值覆蓋舊值。

在您的代碼:

private static String name; 
private static int age; 
private static String type; 

是其中的生物,creature1,creature2共享。

刪除靜態關鍵詞。

public class creatures { 
private String name; 
private int age; 
private String type; 

public creatures(String name, int age, String type) { 
    this.name = name; 
    this.age = age; 
    this.type = type; 
    System.out.println("The creature's name is " + name 
      + " \nThe creatures age is" + age + " \nThe creatures type is " 
      + type); 
} 

public static void main(String[] args) { 
    creatures newcreature = new creatures("Zack", 100, "alien"); 
    creatures newcreature1 = new creatures("Jonny", 500, "vampire"); 
    creatures newcreature2 = new creatures("Dick", 4, "witch"); 
    System.out.println(newcreature.name); 
} 

}

0

你的領域nameagetype是靜態的。這意味着它們被你的所有生物共享。所以你不能說「這個生物的名字是......」,因爲一個生物在你的代碼中沒有名字。正如它寫的,你只能說「生物類有這個名字......」,在Java中寫成creatures.name=...

所以,你需要從你的字段中刪除那個static修飾符。

2

問題在於變量的static關鍵字。

閱讀:enter link description here

靜態變量將得到內存只有一次,如果任何對象改變靜態變量的值,它會保留其價值。