• Post Reply Bookmark Topic Watch Topic
  • New Topic

(e)Static Methods!  RSS feed

 
Kamila Bertran
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys!

I've got a problem with understanding on how to call static and non static methods. There's obviously something I am missing. OK, so for example I've got a piece of code:



Can someone explain me why lines 7,8 and 19 are illegal? I just can't see it. :/

Thanks!
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are a number of things wrong in your code, which make it so that it does not compile - for example, there are typos such as "viod" instead of "void", "Static" instead of "static" (Java is case-sensitive), and forgetting to put a parameter list behind a method name (for the method named "one"). Please post correct code, otherwise it will become harder to help you.

To understand static, see Understanding Class Members in Oracle's Java Tutorials.

Member variables and methods that are static are class-level variables and methods instead of object-level - unlike non-static variables and methods, they don't work on a specific object, but are shared between all objects of the class.

If you have a static method one(), then you cannot call a non-static method three() without specifying on which object you want to call the non-static method. So, that's why line 7 doesn't work.

Likewise, lines 8 and 19. The method four() is non-static. You cannot call it without specifying on which object you are calling the method.
 
A.J. Côté
Ranch Hand
Posts: 417
Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

The compiler should give you clear enough explanations if you try to compile it ;-)

7) Can't call an instance method without an instance (or from a static context).
8) four isn't a static method
19) four isn't a static method, in this case this.four() would work.

I hope this helps a bit.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!