• Post Reply Bookmark Topic Watch Topic
  • New Topic

Relationship of static method to object creation  RSS feed

 
Kevin Kaminski
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I hope I can ask this clearly. I'm not fully understanding the purpose of a static method. Why is it necessary to use them or what situation calls for them?

I have created a simple class that uses getters and setters. When I go back to my main method to call one of the getters, the compiler tells me I cannot make a static reference to a non-static method.







Why does a non-static method only work here when a new object Box is created?

 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66207
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But you have not created a new Box object.
 
Campbell Ritchie
Marshal
Posts: 55793
164
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

As well as those methods you should give your class a constructor. That will insist anybody using it pass a size to your Box. You should also return the size from the get method rather than displaying it.
 
Stefan Evans
Bartender
Posts: 1836
10
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In essence the answer to your question is: Because that is the way it is intended to work by definition.
Variables and methods NEED an instance of the object to exist.
The computer won't allocate space to store a "length" until you create a box.

Static methods are class methods. You call them on the class directly, and they don't need you to create an object first.
They are actually the exception to the general rule.

Because you are in a static context (the main method) then you will need to create an object to call instance methods.
A common pattern is to do that as the only thing in a main method because working within that static context can be very limiting.





  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!