File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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: 230
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: 230

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

Correct.
 
jQuery in Action, 2nd edition
 
subject: Accessing non-static from static method
 
Similar Threads
Accessing Static Member Using Object Reference Variable
Casting doubt
Statement Doubt
Doubt in K&B book page 102 of Java 1.4
When do we invoke a method using a dot notation?