2

1: I have a program like..

public class Test{
    void dispose(){
        System.out.println("disposing");
    }
    Test t=new Test();
    public static void main(String[] args){
        t.dispose();
    }
}

why cant I call dispose method from main()? if its static and non static relation, why the below code works?

public class Test{
    void dispose(){
        System.out.println("disposing");
    }
    public static void main(String[] args){
        Test t=new Test();
        t.dispose();
    }
}

2: should always the method call code shold be in method? because, the below code is not working..

public class Test{
    void dispose(){
        System.out.println("disposing");
    }
    Test t=new Test();
    t.dispose();
    public static void main(String[] args){
    }
}

Please clarify me..

Scis
  • 2,934
  • 3
  • 23
  • 37
user3766874
  • 793
  • 2
  • 6
  • 14

8 Answers8

1

Example 1

You are in a static method (main) and trying to access a non-static variable t. You have declared the variable t as:

 Test t=new Test();

This has created it as a member variable of the class. Instead you need to declare it as:

 static Test t=new Test();

Now the static method can access it (although this is generally not a good way to do things).

Example 2

You are now declaring the variable t as a local variable inside the main method so it is valid to access it from within main.

Example 3

With the exception of initalizer blocks (which you don't need to worry about) all code must go inside a method.

Tim B
  • 40,716
  • 16
  • 83
  • 128
1

I guess you come from a background in Procedural language like C.

Java is different. It's object-orriented.

Coming to your Question . . . .

Ans1: It's correct to say that you don’t necessarily have to create an instance of a class to use the methods of the class. If a method is declared with the static keyword, the method can be called without first creating an instance of the class. That’s because static methods are called from classes, not from objects.

BUT, you can not call non-static method from a static context (here as in static method main()). WHY? Because you can't call something that doesn't exist. Since you haven't created an object, the non-static method doesn't exist yet. A static method (by definition) always exists.

However even that's not the exact case over here

You may feel that you have created an instance of the class at line 5 of your code but to to the compiler, it doesn't exists. It's outside the main() method, which is the first thing looked for in any run-able Java program. The compiler then ropes in other parts as required. You can't have executable code that is not in a method, look at your object initialization. In second block of code, the compiler sees the object initialization, so program executes.

Ans2: YES. As mentioned before, You can't have executable code that is not in a method

Illustration:

class DeclarationTest  
{  
  int a = 5;  
  int b = 10;  
  int c = a + b;//it is Ok, this is a declaration statement for c  

  /* 
  int c; 
  c = a + b; ------> this is not Ok, you are performing an action here this must be inside a method! 
  */  
}

If that was the case it would make having methods a bit less useful. . . Think about it.

Community
  • 1
  • 1
Ashesh
  • 3,499
  • 1
  • 27
  • 44
0

why cant I call dispose method from main()? if its static and non static relation, why the below code works?

Since you have a instance of Test, so you can use that even in static context.

should always the method call code shold be in method?

Yes. exactly. Either in methods, static block or in constructor. Other places not allowed.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

The reason the second block doesn't work is because of the static relation.

If a method is not static, then it must have an instance to be accessed. That is why, creating an instance of the class allows you to call the method.

If you made the dispose method static, then you could directly call the method since there is only a single instance of it.

Here is a link to a different question that explains it well:

calling non-static method in static method in Java

Hope this helps :)

Community
  • 1
  • 1
FreakyDan
  • 559
  • 1
  • 7
  • 24
0

Before starting everything let me clear what is an Class variable and an Object Variable

Class Variable : Static variable, which can be accessed without initializing the Class

Object Variable: non static Variable which can only be accessed on CLass instantiation

So in your case, when the main Gets Called, the Class is not initiated, so the object doesnt get initialized, so you cannot call the dispose method.

Sashi Kant
  • 13,277
  • 9
  • 44
  • 71
0

why cant I call dispose method from main()? if its static and non static relation, why the below code works?

non-static variable t cannot be referenced from a static context(compiler exception). You should always remember that the jvm searches for the main() method and executes it. Methods and blocks are initialized after that. note:- You always compile and run the class which contains the main method.

You are declaring the variable t as a local variable inside the main method so it is valid to access it from within main.

should always the method call code should be in method?

Yes method calls always need to be inside of a method or in the constructor or initialization block, even static block .

Deepanshu J bedi
  • 1,530
  • 1
  • 11
  • 23
0

When a java program is being executed JVM looks for main method. Within the main if you don't write anything nothing will happen.

public class Test{
    void dispose(){
        System.out.println("disposing");
    }
    Test t=new Test();  //That's ok.
    t.dispose();        //causes compilation error
    
    public static void main(String[] args){
         //Executed as soon as you run your program.
    }
}

You want to call dispose(). What do you want? Call dispose() on object of test as t.dispose() or you can call it using Test.dispose();

Method 1:

public class Test{
    void dispose(){
        System.out.println("disposing");
    }
           
    public static void main(String[] args){
        Test t=new Test();  //You need a reference to Test object
        t.dispose();        //to call its methods

    }
}

Is dispose() in Test static? No... So, you must call it by using Test object. If dispose() in Test static? then...

Method 2:

public class Test{
    static void dispose(){
        System.out.println("disposing");
    }
           
    public static void main(String[] args){
        Test.dispose();  // Since dispose() is static.
    }
}

You can't call non static methods by using Class Reference. You must use Class object But you can call static methods by using class objects (not recommended). You should call it using Class Reference.

Method 3: (Not recommended)

public class Test{
    static void dispose(){
        System.out.println("disposing");
    }
           
    public static void main(String[] args){
        Test t = new Test();
        t.dispose();  //Static members should be accessed using class name
    }
}
Community
  • 1
  • 1
Adarsh Singhal
  • 362
  • 1
  • 3
  • 12
0

Yes, you can not call non-static object or variables inside static block. If you declare object as static then your code will work as follow.

public class Test{
    void dispose(){
        System.out.println("disposing");
    }

    static Test t=new Test();

    public static void main(String[] args){
        t.dispose();        
    }
}

You can also try something like below:

public class Test{
    void dispose(){
        System.out.println("disposing");
    }

    {
         dispose();
    }

    public static void main(String[] args){
        Test t=new Test();
    }
}

Also, we can declare object outside method in class but we can not call method outside method or block.