我想知道是否可以从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
}
}
谢谢前进!
答案 0 :(得分:0)
局部变量可在声明它们的块(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
}
}
答案 1 :(得分:0)
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);
}
请注意,tobiBrown
和sarahSora
两者都是Human
,只是eye_colour
不同。 Human humanName = new Human()
创建一个类型为Human
的新对象。每个人都可以拥有自己的eye_colour
,age
和height
。