0

I am just curious why below code doesn't work if we create a object in method and calls the method of class A then it works.

 class Main {
     A a=new A();
     a.method();
     public static void main(String[] args) {

    
     }
     
}

class A{
     public void method(){
         
     }
}

2 Answers2

0

Static methods are kept in "Stack Memory" of Java, While other methods will be stored in "Heap Memory". At the start of running java code, it first refer to Static Memory. As a.method() is in "Heap Memory" it can't be resolved.

So run this to resolve this issue:

 class Main {
     public static void main(String[] args) {
     A a=new A();
     a.method();
    
     }
     
}

class A{
     public void method(){
         
     }
}
SM. Hosseini
  • 171
  • 1
  • 13
0

If a class has a main method in it, and it is the class you want to run, then java always look inside the main method to start executing.

For example in this case,

public class Test {
    public static void main(String[] args) {
        A a = new A();
        a.method();
    }
    public static void method() {
        System.out.println("method() in class Test");
    }
}

class A {
    public static void main(String[] args) {
        Test.method();
    }
    public void method() {
        System.out.println("method() in class A");
    }
}

If I run Test.java, then main method of Test class will execute first and vice versa.

Now there is a way to make java run code before looking into main method of the class. Take a look at following code.

public class Test {
    static {
        A a = new A();
        a.method();
    }
    public static void main(String[] args) {
        System.out.println("main() of Test executing");
    }
}

class A {
    public void method() {
        System.out.println("method() in class A");
    }
}

The use of static{...} in the class makes executing the code within static block first and then the main block. It is called the static initializer is a static {} block of code inside java class, and run only one time before the constructor or main method is called.

It is a block of code static { ... } inside any java class, and executed by virtual machine when class is called.

  • No return statements are supported.
  • No arguments are supported. -No this or super are supported.

Usually this can be used anywhere. But I see most of the time it is used when doing database connection, API init, Logging and etc.

ahrooran
  • 931
  • 1
  • 10
  • 25