如何从静态块创建对象? [英] How can an object be created from a static block?

查看:61
本文介绍了如何从静态块创建对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在默认包中考虑两个类:

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");
        }


    }       

编译TrialExe:javac TrialExe

Compiling TrialExe: javac TrialExe

如何编译?考虑到Trial对象是从静态块创建的,要创建对象,需要Trial的构造函数,但据我所知,我们无法从静态方法访问非静态方法,并且构造函数是非静态的.

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.

推荐答案

静态方法不能调用非静态方法或字段.没错.

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.

这样想:

  • 静态方法属于该类.只有其中之一,不需要构造.
  • 实例(非静态)方法属于对象实例.

因此,由于没有封装实例,因此无法从静态方法调用实例方法.但是,静态方法可以创建一个对象,然后调用该实例的方法.

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.

这篇关于如何从静态块创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆