静态对象如何访问非静态字段,即使它被定义为静态字段?

时间:2017-08-05 19:04:05

标签: java static

静态对象如何访问非静态字段,即使它被定义为静态字段?

>>> from random import choice

>>> from itertools import count

>>> from operator import itemgetter

>>> values = (0, 15, 30, 45, 60)

>>> length = 6

>>> non_zero_tuples_generator = filter (any, map (lambda _ : tuple (choice (values) for _ in range (length)), count ()))

>>> first_6_tuples = tuple (map (itemgetter (1), zip (range (6), non_zero_tuples_generator)))

((0, 60, 0, 60, 60, 60), (0, 45, 15, 60, 60, 30), (0, 0, 0, 0, 45, 30), (30, 15, 60, 30, 30, 60), (0, 30, 45, 0, 60, 30), (15, 60, 60, 0, 45, 60))

3 个答案:

答案 0 :(得分:0)

hjstatic类的pp字段。但它也引用了pp的实例。

因此,您可以使用hj访问pp类的任何实例成员(方法或字段)。

但是如果你试图访问实例字段:

int y = 8;
以这种方式从static main method()

public static void main(String[] args) {
    System.out.println(y);
}

您将看到,static成员无法引用实例成员。

答案 1 :(得分:0)

 public static pp hj = new pp();
  

静态对象如何访问非静态字段,即使它被定义为静态字段?

这里只是对象的引用是静态的,这意味着要访问那个变量(hj),你不需要创建它的所有者的对象。

获得对象的引用后,您可以访问对象成员,尽管它是静态或非静态引用。

答案 2 :(得分:0)

只要您拥有 static 实例,就可以从静态上下文(例如y)访问非静态成员,例如main正在访问非静态成员。

在您的情况下,hj是一个静态实例。它可以从静态上下文以及y访问,这是它的非静态字段。

相反,如果您尝试在没有对象引用的静态上下文中访问y,则代码将无法编译:

public class pp {
    static int x = 4;
    int y = 8;
    static int z = y + 5; // <<=== This does not compile

    public static void main(String[] args) {
        System.out.println(y); // <<=== This does not compile either
    }
}