Shweta Gulati
Shweta Gulati

Reputation: 7

Static method in java can call non static method

It is said in java that we can not call a non-static method from a static method..what does this mean exactly ?we can always call a non static method frm static one using object although..'pls explan

Upvotes: 0

Views: 81

Answers (2)

ASKASK
ASKASK

Reputation: 667

Here is a nice code piece to illustrate what it means:

class MyClass{

    static void func1(){
        func2(); //This will be an error
    }

    void func2(){
        System.out.println("Hello World!");
    }

}

Upvotes: 1

DNA
DNA

Reputation: 42597

To call a non-static method, you need an instance (object) - because these methods belong to an instance, and in general only make sense in the context of an instance.

Static methods don't belong to an instance - they belong to the class. So there is no need to create an instance first, you can just call MyClass.doSomething()

void foo(){
  MyClass.doSomething();
}

But you can call a non-static method from a static method provided you first create an instance.

static void bar(){
  MyObject o = new MyObject();
  o.doSomething();
}

Upvotes: 0

Related Questions