每@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」。
通過獲取和setter。 – Maroun
你可以在你的'Two'類中創建一個getter/setter – Bennyz
[getter和setter如何工作?](http://stackoverflow.com/questions/2036970/how-do-getters-and-setters-工作) –