2016-09-17 65 views
2

One.java如何使用值從一個類爲其他類呼叫從主要方法

public class One { 
    String asd; 

    public class() { 
     asd="2d6" 
    }  

    public static void main(String args[]) { 
     Two a = new Two(); 
    } 
} 

Two.java

public class Two { 
    ArrayList<String>data; 
    String asd; 

    public Two(String asd){ 
     this.asd=asd; 
     data.add(this.asd);  
    } 
} 

如何使用這個ASD值第二類是從第一類的主要方法調用第三類。

**Third class** 
+0

通過獲取和setter。 – Maroun

+0

你可以在你的'Two'類中創建一個getter/setter – Bennyz

+2

[getter和setter如何工作?](http://stackoverflow.com/questions/2036970/how-do-getters-and-setters-工作) –

回答

3

每@Maroun Maroun和@Bennyz的評論,你可以創建你的兩個類中的getter和setter方法:同時編碼(這樣不僅

import java.util.ArrayList; 
public class Two { 

    ArrayList<String> data; 
    String asd; 

    public Two(String asd) { 
     this.asd = asd; 
     data = new ArrayList<>(); //<-- You needed to initialize the arraylist. 
     data.add(this.asd); 
    } 

    // Get value of 'asd', 
    public String getAsd() { 
     return asd; 
    } 

    // Set value of 'asd' to the argument given. 
    public void setAsd(String asd) { 
     this.asd = asd; 
    } 
} 

一個不錯的網站,瞭解這個閱讀),是CodeAcademy

要在第三類中使用它,你可以這樣做:

public class Third { 
    public static void main(String[] args) { 
     Two two = new Two("test"); 

     String asd = two.getAsd(); //This hold now "test". 
     System.out.println("Value of asd: " + asd); 

     two.setAsd("something else"); //Set asd to "something else". 
     System.out.println(two.getAsd()); //Hey, it changed! 
    } 

} 


也有一些事情不能說得對,你的代碼:

public class One { 
    String asd; 

    /** 
    * The name 'class' cannot be used for a method name, it is a reserved 
    * keyword. 
    * Also, this method is missing a return value. 
    * Last, you forgot a ";" after asd="2d6". */ 
    public class() { 
     asd="2d6" 
    }  

    /** This is better. Best would be to create a setter method for this, or 
    * initialize 'asd' in your constructor. */ 
    public void initializeAsd(){ 
     asd = "2d6"; 
    } 

    public static void main(String args[]) { 
     /** 
     * You haven't made a constructor without arguments. 
     * Either you make this in you Two class or use arguments in your call. 
     */ 
     Two a = new Two(); 
    } 
} 


%的評論@ cricket_007, public class()方法的更好的解決方案是:

public class One { 

    String asd; 

    public One(){ 
     asd = "2d6"; 
    } 
} 

這樣,當生成One對象(One one = new One)時,它的asd字段已包含「2d6」。

+0

我看到'公共類()'的評論,但也許你可以修復它? –

+1

'data.add(this.asd);'有一個NullPointerException異常 –

+0

@ cricket_007刪除'public class()'並使用'public void initializeAsd()'方法。 NullPointerException發生'因爲ArrayList數據沒有初始化,現在是。 –