简体   繁体   中英

How can a static object access non-static fields even though it's defined as static?

How can a static object access non-static fields even though it's defined as static?

public class pp {
    static int x = 4;
    int y = 8;
    public static pp hj = new pp();

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

hj is a static field of the pp class yes. But it refers also an instance of pp .

So you can use hj to access to any instance member (method or field) of the pp class.

But if you try to access to the instance field :

int y = 8;

from the static main method() in this way:

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

you will see that you cannot as a static member cannot refer to an instance member.

 public static pp hj = new pp();

How can a static object access non-static fields even though it's defined as static?

Here just the reference to the object is static which means that to access that varaible ( hj ) you need not to create an object of it's owner.

Once you got the reference to the object you can access the object members though it is static or non static reference.

You can access a non-static member, such as y , from static context, such as main , as long as you have a static instance from which you are accessing the non-static member.

In your case, hj is a static instance. It can be accessed from static context, along with y , which is its non-static field.

In contrast, if you were to attempt accessing y in static context without an object reference, your code would fail to compile:

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

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