java 对象传递给方法_java – 将对象值传递给方法
由于您具有在Plant類中定義的averageLeaves(),因此您必須實際從其中一個工廠實例調用方法.這是你應該怎么做的.
plantA.averageLeaves();
你在這里犯的一個大錯誤是,
sumLeaves = leaves + leaves;
這實際上增加了特定(一個)植物實例的葉子,這是錯誤的.你必須實際傳遞差異實例中的葉子數.
這是一個使用getter& amp;和更好的方法來做到這一點. setter方法.將averageLeaves()方法設為靜態也是有意義的.這樣您就不需要實例來調用該方法.
public class Plant {
int leaves;
int age;
//int sumLeaves; you do not need them now, as the averageLeaves method is static
//double average;
static void averageLeaves (int leaves1, int leaves2) {
int sumLeaves = leaves2 + leaves1; //here is where I need help
double average = (double) sumLeaves / 2;
System.out.println("The average number of leaves is: " + average);
}
void setLeaves(int leaves){
this.leaves = leaves;
}
int getLeaves(){
return this.leaves;
}
}
public class Main {
public static void main(String[] args) {
Plant plantA = new Plant();
plantA.setLeaves(5);
Plant plantB = new Plant();
plantB.setLeaves(3);
Plant.averageLeaves(plantA.getLeaves(), plantB.getLeaves());
}
}
總結
以上是生活随笔為你收集整理的java 对象传递给方法_java – 将对象值传递给方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java百度云推送demo_百度云推送j
- 下一篇: 暗黑再临Java正版_暗黑破坏神之墨菲斯