日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

java 对象传递给方法_java – 将对象值传递给方法

發布時間:2025/5/22 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 – 将对象值传递给方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。