在Java类中获取第n个对象

时间:2015-03-07 00:55:45

标签: java class object

如果我有这段代码:

public class Foo{
    public static void main(String[] args){
    String hello = "Hello World";
    int num = 7;
        }
    }

如果我想打印出String hello和int num,我通常会这样做:

System.out.println(hello);
System.out.prinln(num);`

但是,我可以用不同的方式访问hello和num,例如:

Foo(0); // for String hello
Foo(1); //for int num

1 个答案:

答案 0 :(得分:1)

由于hellonummain()内声明,现在您可以使用类名访问它,因为它们不会超出main()的范围。< / p>

我猜你可能会要求数组:

public static void main(String[] args) {
    Object[] foo = {"hello world", 7};
    System.out.println(foo[0]);//hello world
    System.out.println(foo[1]);//7
}