beoliver
beoliver

Reputation: 5759

java class object and Types

Given a class

public class A {
  public static int classVal;
}

During run-time, does the type A become a reference to a class Object?

public static void main(String[] args) {
  A a = new A(); 
  A.classVal = 100;
  A.classVal = 200;
}

if A.classVal is a reference to static Class variable, then is A a reference to an Object that represents the class?

does a.getClass() refer to the same object as A?

To clarify

if A.classVal is a reference, and A is nothing more than a name, does a class just become part of a lookup table that uses the class name as a key? I am trying to understand what happens to a class at run-time.

Upvotes: 2

Views: 92

Answers (4)

Kenny Tai Huynh
Kenny Tai Huynh

Reputation: 1599

No, the "A" is just the class. It is not a reference. "a" is an reference object. So, in case you would like to check the class, just compare: a.getClass() vs A.class. They should be equal.

Upvotes: 1

tonychow0929
tonychow0929

Reputation: 466

No. A is a class name, but A.class equals a.getClass().

Upvotes: 1

Akash Thakare
Akash Thakare

Reputation: 22972

First of all,

static refers to the enclosing type and not to the instances

No A does not become a reference to a class Object. Each static member will be created for the type itself and for all the instances of the class the same copy will be used during the execution if you try to access the static member with instance.

It's a way to access the static member in Java with the name of class here A.staticMember.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499770

No, A isn't a reference at all. It's just the class name. A is not an expression in its own right - it doesn't have a value. It can only be part of another expression (like A.classVal or new A()).

Upvotes: 3

Related Questions