简体   繁体   中英

Accessing a local variable from another class

I was wondering if it is possible to access a local variable from another class in Java. I have tried to do it in the below code, however, it is giving an error. Please clarify whether this is possible, and how it may be done if it is.

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
    }
}

Thanks is advance!

Local variables are accessible inside the block (if-else/for/while) where they are declared. If you want to use any variables that belong to other classes, you can use static variables.

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

    public static void main()
    {
    }

}

And you can access it in other classes like:

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() is a Method and can only return one value of a certain type or nothing. Everything else is lost after the method ends. Currently your return type is void thus returning nothing. If you change your return type from void to String and return the eye color you can use it.

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);
}

Does this make sense through? Id say no. We want every human to have his own eye color. So if you have a human called Tobi_Brown with brown eye color, how can this be expressed with java code?

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);
}

Notice how tobiBrown and sarahSora are both Human with just different eye_colour . Human humanName = new Human() creates a new object of type Human . Every human can have his own eye_colour , age and height .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM