Static And Non Static Method Intercall In Java

Vishal picture Vishal · Jul 9, 2012 · Viewed 17.4k times · Source

I am clearing my concepts on Java. My knowledge about Java is on far begineer side, so kindly bear with me.

I am trying to understand static method and non static method intercalls. I know --

  1. Static method can call another static method simply by its name within same class.
  2. Static method can call another non staic method of same class only after creating instance of the class.
  3. Non static method can call another static method of same class simply by way of classname.methodname - No sure if this correct ?

My Question is about non static method call to another non staic method of same class. In class declaration, when we declare all methods, can we call another non static method of same class from a non static class ?
Please explain with example. Thank you.

Answer

Talon876 picture Talon876 · Jul 9, 2012

Your #3, is correct, you can call static methods from non-static methods by using classname.methodname.

And your question seems to be asking if you can call non-static methods in a class from other non-static methods, which is also possible (and also the most commonly seen).

For example:

public class Foo {

public Foo() {
    firstMethod();
    Foo.staticMethod(); //this is valid
    staticMethod(); //this is also valid, you don't need to declare the class name because it's already in this class. If you were calling "staticMethod" from another class, you would have to prefix it with this class name, Foo
}

public void firstMethod() {
    System.out.println("This is a non-static method being called from the constructor.");
    secondMethod();
}

public void secondMethod() {
    System.out.println("This is another non-static method being called from a non-static method");

}

public static void staticMethod() {
    System.out.println("This is the static method, staticMethod");
}
}