• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Bear Bibeault
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • salvin francis
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Frits Walraven
Bartenders:
  • Jj Roberts
  • Carey Brown
  • Scott Selikoff

Accessing non-static from static method

 
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic