[英]Create an object and put in an array
我只想創建一個對象,我不確定我是否正在創建並且它是對的。我的例子,假設我有 2 個類(用戶輸入和紙張)。0fcourse 有和 main。在這個例子中沒有繼承(只是2個簡單的類)。我創建了一個對象嗎?我如何將它放入數組或同一個數組中?
package exercise;
public class Exercise{
static int N; //from keyboard .I have a class userinput.It doesnt need to write it here ,i have in the other class the problem
public static void main(String[] args) { // main class
Paper[] pin = new Paper[N]; //i create an array
Paper.setpencil(3); // i wrote the 3 .In this way i create 3 pencil?
Paper.getpencil(3);
Paper.setsomething(4); // i wrote the 4 .I create 4 ?
Paper.getsomething(4);
} }
public class Paper{ //in this class i am confused
public Paper(){} //default constructor
private int pencil;
private String something;
public int getpencil(){
return pencil;
}
public void setpencil(){
pencil=UserInput.getInteger():
}
public int getsomething(){
return something;
}
public void setsomething(){
something=UserInput.setInteger();
}
}
有了這個聲明:
Paper[] pin = new Paper[N];
你創建了一個 Paper 類的對象數組。
您還必須為每個數組元素創建一個對象,例如:
for (int i=0; i < N, i++)
{
pin[i] = new Paper();
}
接下來,您應該以這種方式引用數組的一個元素(例如,索引為 0 的第一個元素):
pin[0].setpencil(3);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.