Posted by Unknown on 5:27 PM
Labels:

Accessing Static Methods and Variables:

Since you don't need to have an instance in order to invoke a static method or access a static variable, then how do you invoke or use a static member? What's the syntax? We know that with a regular old instance method, you use the dot operator
on a reference to an instance:

class Frog {

int frogSize = 0;

public int getFrogSize() {

return frogSize;

}

public Frog(int s) {

frogSize = s;

}

public static void main (String [] args) {

Frog f = new Frog(25);

System.out.println(f.getFrogSize()); // Access instance

// method using f

}

}

In the preceding code, we instantiate a Frog, assign it to the reference variable f, and then use that f reference to invoke a method on the Frog instance we just created. In other words, the getFrogSize() method is being invoked on a specific Frog object on the heap. But this approach (using a reference to an object) isn't appropriate for accessing a static method, because there might not be any instances of the class at all! So, the way we access a static method (or static variable) is to use the dot operator on the class name, as opposed to using it on a reference to an instance, as follows:

class Frog {

static int frogCount = 0; // Declare and initialize

// static variable

public Frog() {

frogCount += 1; // Modify the value in the constructor

}

}

class TestFrog {

public static void main (String [] args) {

new Frog();

new Frog();

new Frog();

System.out.print("frogCount:"+Frog.frogCount); //Access

// static variable

}

}

But just to make it really confusing, the Java language also allows you to use an object reference variable to access a static member:

Frog f = new Frog();

int frogs = f.frogCount; // Access static variable

// FrogCount using f


In the preceding code, we instantiate a Frog, assign the new Frog object to the reference variable f, and then use the f reference to invoke a static method! But even though we are using a specific Frog instance to access the static method, the rules haven't changed. This is merely a syntax trick to let you use an object reference variable (but not the object it refers to) to get to a static method or variable, but the static member is still unaware of the particular instance used to invoke the static member. In the Frog example, the compiler knows that the reference variable f is of type Frog, and so the Frog class static method is run with no awareness or concern for the Frog instance at the other end of the f reference. In other words, the compiler cares only that reference variable f is declared as type Frog.

0 comments: