2016-11-27 117 views
-6

我不知道如何把這個,但即時通訊試圖獲得在一個字段中的值的價值。下面是一些代碼(不要問我爲什麼長度和高度):Java - 在領域獲得價值?

//person class 
public person(double w, double h, double l){ 
     this.width = w; 
     this.height = h; 
     this.length = l; 
    } 

//age class (extends person) 
    public age(double w, double h, double l, int a) { 
     super(w, h, l); 
     this.age = a; 
    } 

//Creating the objects and putting them in an array (in the main class): 
public person steve = new age(36.64, 185.64, 44.4, 26); 
public person paul = new age(45.64, 178.64, 53.4, 47); 

person[] people = new person[2]; 
people[0] = steve; 
people[1] = paul; 

現在我需要得到人們的年齡在數組中。你會怎麼做?

+0

爲什麼你創建一個具有年齡構造函數的人? – habsq

+0

你的年齡在哪裏?似乎它延伸人,它有getters,setters?發佈代碼 – developer

+1

*僅供參考:* [Java命名約定](http://stackoverflow.com/documentation/java/2697/oracle-official-code-standard/9031/naming-conventions#t=201611272151346697502)適用於類名以大寫字母開頭,即'Person'和'Age'。 – Andreas

回答

0

希望這有助於你瞭解:)

class Main { 
    public static void main(String[] args) { 
    Person pixelGrid = new Person(); 
    pixelGrid.setName("Pixel Grid"); 
    pixelGrid.setAge(18); 
    System.out.println(pixelGrid); 
    } 
} 

class Person { 
    protected String sName; 
    protected int sAge; 

    public void setName(String sName) { 
     this.sName = sName; 
    } 

    public String getName() { 
     return sName; 
    } 

    public void setAge(int sAge) { 
     this.sAge = sAge; 
    } 

    public int getAge() { 
     return sAge; 
    } 

    public String toString() { 
     String s = "The Persons Name is: " + getName() + "\n"; 
     s += "Their Age is: " + getAge() + "\n"; 
     return s; 
    } 
} 

輸出:

The Person's Name is: Pixel Grid 
Their Age is: 18 

試試吧here!

0

要直接從陣列中檢索年齡:

一些小碼更改爲主類:

public static void main(String[] args) { 
    // TODO Auto-generated method stub 


     age steve = new age(36.64, 185.64, 44.4, 26); 
     age paul = new age(45.64, 178.64, 53.4, 47); 
     age[] people = new age[2]; 
     people[0] = steve; 
     people[1] = paul; 

     System.out.println(people[0].age); 
     System.out.println(people[1].age); 
} 
+0

必須陳述思想,建議使用getters和setters來檢索實例變量 - 根據下面的shash678建議 – Adnan