2015-01-10 46 views
-2

我不知道這是否是一種錯誤的提問方式,因爲它實際上是我在另一個question中得到的提示的延續。我瞭解嗎?

事情是,我想知道靜態關鍵字做了什麼,我想我明白了。我現在的問題是,我理解正確嗎?我如何創建「狗」的實例?

class Dog { 
static String form /* of all dogs */ = "Doggy-like"; 
static int quantity /* of dogs */ = 5; 

String colour; /* of a specific dog */ 
String size; /* of a specific dog */ 

} 

class Cat { 
static String form /* of all cats */ = "Catty-like";  
static int quantity/* of cats */ = 3; 

String colour; /* of a specific cat */ 
String size; /* of a specific cat */ 


} 

public class Animals { 
public static void main(String[] args){ 
    System.out.println("There are "+Cat.quantity+" cats."); 
    System.out.println("There are "+Dog.quantity+" dogs."); 
    /* EDIT: */ 
    Dog Mike = new Dog(); 
    Dog Pete = new Dog(); 
    Cat Sushi = new Cat(); 
    Cat Michael = new Cat(); 
    Cat Pete = new Cat(); 
    Dog.Mike.size="Big"; 
    Dog.Mike.colour="Red"; 
    Dog.Pete.size="Small"; 
    Cat.Sushi.size="Small"; 

    } 
} 

我也想知道這些皮特貓和狗之間是否存在衝突,以及如果這樣定義它們的尺寸是正確的。在公共類動物中,或者在他們各自的類(或者其他類)中創建它有什麼不同?

+0

看起來像。你可以通過調用正確的構造函數來創建一個類的實例,在這種情況下,它將是'Dog dog = new Dog();'。 –

+0

不是你的低調選民,但請注意,因爲你已經提出了幾個已經投票表決的問題,如果發生這種情況太多,網站軟件會自動阻止你提出進一步的問題。如果你還沒有這樣做,請通過[遊覽],[幫助]和[如何提出一個很好的問題](http://stackoverflow.com/help/how-to-ask)部分到看看這個網站是如何工作的,並幫助你改善你現在和未來的問題,從而希望避免這個禁令。 –

+0

現在爲下一課,介紹一類動物作爲狗和貓的延伸。 – wvdz

回答

2

是的,您已經在類中定義了靜態字段並使用ClassName.fieldName在靜態上下文中訪問它。所以你是對的。

如果你想要實例狗,你可以在你的主喜歡這樣做:

Dog dog = new Dog(); 

默認情況下,我們得到的構造函數不接受任何參數/ S。