-4

Hi after a long time i am learning java , i have a confusion in calling the method without the help of the object.

public class VariablesInJava {

int instanceField=5;

static String staticField = "apple";

public void method() {

final String localVariable = "Initial Value";

    System.out.println(localVariable);

}

public static void main(String args[]) {

    VariablesInJava obj = new VariablesInJava();

    System.out.println(obj.instanceField);
    System.out.println(obj.staticField);
    System.out.println(VariablesInJava.staticField);
    System.out.println(new VariablesInJava().instanceField);
    obj.method();

}

}

How can i call the method() without the help of object ?

  • Methods are part of objects. Methods can't exist without objects. That's like asking for a tutorial on driving a car without wheels. --- Although you should look at static methods. – byxor Dec 10 '16 at 07:05
  • You can define your methods to be static. But you should know when to use one: http://stackoverflow.com/questions/2671496/java-when-to-use-static-methods http://stackoverflow.com/questions/2080150/when-should-i-use-static-methods-in-a-class-and-what-are-the-benefits – denvercoder9 Dec 10 '16 at 07:07

2 Answers2

0

You can create a static method and call the method without creating an object of that class.

Akhil Nambiar
  • 315
  • 3
  • 18
0

Since main method is a static method you either need to create an object of class VariablesInJava and then call it or make the "method" static. Do this :

public static void method()

Now you can simply call method() without creating an object.

Hope that helps.

jkasper
  • 236
  • 4
  • 19