How can an object be created from a static block?

对着背影说爱祢 提交于 2021-02-19 03:14:42

问题


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.


回答1:


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.




回答2:


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.




回答3:


A class cannot access its own non- static methods from inside a static method. But there's no issue with creating an instance of an object and accessing that object's methods. In fact you could even create an instance of TrialExe in the main method.



来源:https://stackoverflow.com/questions/25901202/how-can-an-object-be-created-from-a-static-block

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!