Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

The word "Static" in method declaration.  RSS feed

 
WeiJie Lim
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When we include static as part of the method declaration, (eg: public static void method1() ) , it means that you can call it without first creating an instance of the class in which it’s defined.

That is what I understand from some Java books and what I read online.

However, I tried to implement a method without the static keyword to test it out, but to no avail. There will always be an error of "non-static method cannot be referenced from a static context" .





 
Rameshwar Soni
Ranch Hand
Posts: 247
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
WeiJie Lim wrote:When we include static as part of the method declaration, (eg: public static void method1() ) , it means that you can call it without first creating an instance of the class in which it’s defined.


This is true. But when there is no static keyword in the part of method declaration then such methods are to be called or invoked by creating an instance of the class in which it’s defined.

Therefore in your case it has to be
 
Rameshwar Soni
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
WeiJie Lim wrote:.




One more thing there is no need to create PlayWithString class Object in method1() as far as your current problem is concerned i.e. calling the method1().
 
WeiJie Lim
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks alot. I actually wanted to call the method, but I didn't know how to go about doing it.

Thanks for clearing up my confusion.
 
Campbell Ritchie
Marshal
Posts: 55672
161
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A static member is one which belongs to the class, not the object. You should have a look at this very dubious classification of methods. Rememebr you can only override instance methods, so anything abstract or overridden or implemented from an interface cannot be static.
You cannot access an instance field or method from a static method, nor use the keywords this and super.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!