2016-09-17 77 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数据没有初始化,现在是。 –