aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Accessing non-static from static method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Accessing non-static from static method" Watch "Accessing non-static from static method" New topic
Author

Accessing non-static from static method

Pranav Bhatt
Ranch Hand

Joined: Mar 20, 2006
Posts: 284
Hi all,
It seems as i'am moving forward to newer chapters i'm forgetting the previous ones . Here's one question from Kathy & Bates. They have stated that-: A static method of a class can't access a nonstatic (instance) method or variable of its own class. But the following program is doing the same i guess.. please clarify!!!


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());
}
}

here the static method main is accessing the nonstatic method getFrogSize of same class(Frog)....

[ December 11, 2007: Message edited by: pranav bhatt ]
[ December 11, 2007: Message edited by: pranav bhatt ]
Jari Timonen
Ranch Hand

Joined: Jan 16, 2004
Posts: 232
Your code is using instance variable to call the method. That is legal.
(You cannot say: getFrogSize())



SCJP 5.0, SCJD URLyBird 1.3.3, OCMJEA 5 (SCEA) Factory Homes
Pranav Bhatt
Ranch Hand

Joined: Mar 20, 2006
Posts: 284
Yes i was suspecting this, so that means you can use instance variable to call nonstatic mehthods from static reference..means static methods.??
Jari Timonen
Ranch Hand

Joined: Jan 16, 2004
Posts: 232

Yes i was suspecting this, so that means you can use instance variable to call nonstatic mehthods from static reference.

Correct.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Accessing non-static from static method