簡體   English   中英

從另一個類訪問局部變量

[英]Accessing a local variable from another class

我想知道是否可以從 Java 中的另一個類訪問局部變量。 我試圖在下面的代碼中做到這一點,但是,它給出了一個錯誤。 請說明這是否可行,如果可行,如何進行。

class Human
{
    int age;
    int height;

    public static void main2()
    {
        String eye_colour="Blue";
    }

}
class Tobi_Brown 
{
    public static void main()
    {


Tobi_Brown a=new Tobi_Brown();

        System.out.println("The eye colour is " + Human.main2().eye_colour);//Accessing eye_colour
    }
}

感謝提前!

局部變量可在聲明它們的塊(if-else/for/while)內訪問。 如果要使用屬於其他類的任何變量,可以使用靜態變量。

class Human
{
    public static String eye_color = "Blue";
    int age;
    int height;

    public static void main()
    {
    }

}

您可以在其他類中訪問它,例如:

class Tobi_Brown 
{
    public static void main()
    {


Tobi_Brown a=new Tobi_Brown();

        System.out.println("The eye colour is " + Human.eye_colour);//Accessing eye_colour
    }
}

main2()是一個方法,只能返回某個類型的一個值或什么都不返回。 方法結束后,其他所有內容都將丟失。 目前,您的返回類型為void因此不返回任何內容。 如果將返回類型從void更改為String並返回眼睛顏色,則可以使用它。

public class Human {

    public static String main2() {
        String hairColor = "Red";
        String eye_colour = "Blue";
        return eye_colour;
        // hairColor is now lost.
    }

}

// In another class or the same.
public static void main(String[] args) {
    String eyeColor = Human.main2();
    System.out.println("The eye colour is " + eyeColor);
}

這有意義嗎? 我說不。 我們希望每個人都有自己的眼睛顏色。 所以如果你有一個叫Tobi_Brown的人,他的眼睛是棕色的,這怎么用 java 代碼來表達呢?

public class Human {

    public String eyeColor;
    public int age;
    public int height;

}

// Again in another class or the same.
public static void main(String[] args) {
    Human tobiBrown = new Human();
    tobiBrown.eyeColor = "brown";
    Human sarahSora = new Human();
    sarahSora.eyeColor = "Sky blue";
    System.out.println("The eye colour is " + tobiBrown.eyeColor);
    System.out.println("The eye colour is " + sarahSora.eyeColor);
}

注意tobiBrownsarahSora都是Human ,只是eye_colour不同。 Human humanName = new Human()創建一個類型為Human的新對象。 每個人都可以擁有自己的eye_colourageheight

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM