Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can an object be created from a static block?

Consider two classes in a default package :

    class Trial {
        int a;
        int b;

        public static void main (String [] args){
            System.out.println("test base");

        }


    }

    public class TrialExe {
        int a;
        int b;

        public static void main (String [] args){
            Trial t = new Trial();
            System.out.println("test exe");
        }


    }       

Compiling TrialExe: javac TrialExe

How can this compile?. Considering that the Trial object is created from a static block, to create an object the constructor of Trial is required, but as far as I know we cannot access a non static method from a static method and the constructor is non static.

like image 375
19 revs, 10 users 67% Avatar asked Sep 17 '14 22:09

19 revs, 10 users 67%


2 Answers

A static method cannot call a non-static method or field. That is correct.

But constructors are special. You can construct a new object from within a static method and then you can call that object's methods, even if they are not static and even if that object is an instance of the same class.

Think of it this way:

  • Static methods belong to the class. There is just one of them and they don't need to be constructed.
  • Instance (non-static) methods belong to the object instance.

Because of this, you cannot call an instance method from a static method because there is no encapsulating instance. However, a static method can create an object and then call that instance's methods.

like image 120
nostromo Avatar answered Sep 30 '22 05:09

nostromo


A static method cannot call a non-static method or field but a non-static method can call a static method or field.

Constructor is not same as other instance method, it is different. That's why you can create object within the static method.

like image 25
Moni Avatar answered Sep 30 '22 06:09

Moni