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

Static Method  RSS feed

 
Nik Raut
Greenhorn
Posts: 22
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it true that static methods can call only static methods? If yes, then how do we call non-static methods from main() method?
 
Marcelo Ortega
Ranch Hand
Posts: 528
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes it's true, nut not only static methods, we can also call static fields.
In order to call a non-static method from a static method we must create an object of the non-static method's enclosing class.

Cheers, Marzo.
 
Joyce Lee
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anikanchan: If yes, then how do we call non-static methods from main() method?

Like this:


Joyce
 
newgen pras
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If static method can be called from another static method ..how does this code works .. pls explain me ..

 
Srinivasa Raghavan
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because a static method is being called from a non static method and not the other way round.
 
Akhilesh Trivedi
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Absolutely true Anikanchan!
You can never have non-static code inside a static block.

Looking at the example....


public class Cow
{
public static void main(String[] args) {
Cow c = new Cow();
c.moo();
}

// an instance method
public void moo() {
System.out.println("where is my dinner?");
}
}


I guess it is running fine because the object c is created within the main() itself i.e. whatever be the case "c" will have its scope only and only within main(). So there is no point in saying "c" as a static or non-static thing.

I dont know but i think if we have "Cow C" declare outside somewhere and used inside main (why just main, any static method) then there must be an alarm!!!

Well, I havent tried it any comments guys.......
 
janki tangeda
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
newgen pras,

Is the result of ur program 20 20?
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!