• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing non-static from static method

 
Pranav Bhatt
Ranch Hand
Posts: 284
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 232
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your code is using instance variable to call the method. That is legal.
(You cannot say: getFrogSize())

 
Pranav Bhatt
Ranch Hand
Posts: 284
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 232
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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

Correct.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic