This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

static vs non-static methods  RSS feed

 
Kathy Talley
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have read several entries in books about the difference between static and non-static methods, but I don't understand what is being talked about. There are a couple of entries on this site I read through and don't understand either. Can someone explain the difference very thoroughly and simply? I have read that you don't need an object to call a static method, and that you do need to create an object so that you can use it to access a non-static method. But I don't understand what this means... Help please!
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See if this helps...
a static method is called by referring to the CLASS name, and then the method. One example is the Math class. you can NEVER have a Math object, the compiler won't let you say

but the Math class has lots of methods i want to use. since all the methods are static, i can call them like so:

Similary, your main() method MUST be static.
a non-static method must be called from a specific instance of a class. for example, the String class has a method with the signiatur

this tells you what character is at a specific position within a string. So, it's obvious i NEED a string to use this. it would make no sense to say

What string are we looking in? i need something like

notice this time, i called the method by using an actual object (more precisely an object reference), not the CLASS name.
does that help?
[ March 08, 2004: Message edited by: fred rosenberger ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!