This week's book giveaway is in the Game Development forum.
We're giving away four copies of Badass: Making Users Awesome and have Kathy Sierra on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Problem with static method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Badass: Making Users Awesome this week in the Game Development forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Problem with static method" Watch "Problem with static method" New topic

Problem with static method

ronnir paterl

Joined: Oct 18, 2007
Posts: 11
I came across this line in Khalid Mughal's book and I don't understand it.

"However, note that a static method in a class can always use a reference of the class's type to access its members, regardless of whether these members are static or not."

Please consider the foll. code.

class Test {
int no;

public static void main(String args[]) {
Test a; = 10;

Shouldn't work as I'm using reference of class type (a) to access its non static member (no).

Can someone please clarify this for me...

amit punekar
Ranch Hand

Joined: May 14, 2004
Posts: 534
You need to instantiate Test i.e

and then use this reference to access any non static member variable of the class.

The note you mentioned said "reference of class's type to access its members ...". You should read it as "Initialized reference of class's type if that is what is causing confusion to you.
Hope that answers your question.

Xyz Abc

Joined: Aug 24, 2007
Posts: 27
Amit is right, you need to instantiate test by using new.

[ December 01, 2007: Message edited by: Xyz Abc ]
Consider Paul's rocket mass heater.
subject: Problem with static method