为什么可以在其定义内实例化一个类? [英] Why Can You Instantiate a Class within its Definition?

查看:44
本文介绍了为什么可以在其定义内实例化一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个同事(Java的新手)今天停下来,问了一个看起来很简单的问题.不幸的是,我为向他解释做了一件绝对可怕的工作.他有一本书,上面的代码看起来像这样:

A coworker (who is very new to Java) stopped in today and asked what seemed like a very simple question. Unfortunately, I did an absolutely horrible job of trying to explain it to him. He had a book that had a little code that looked like this:

class XCopy {

    public static void main(String[] args) {
        XCopy x = new XCopy(); // 1
        x.doIt();
    }

    public void doIt() {
        // Some code...
    }
}

他在第1行上感到困惑.他想知道的是,为什么可以在类XCopy的定义中创建XCopy的新实例.他认为这会带来某种前向引用错误.毕竟,我们还没有完成XCopy类的声明,那么我们如何创建一个呢?

He was confused on line 1. What he wanted to know was why a new instance of XCopy could be created within the definition of the class XCopy. He thought this would have given some sort of a forward referencing error. After all, we hadn't yet finished declaring what the class XCopy was, so how could we create one?

我当然知道这是有效的代码,但是,当我试图向他解释时,我发现自己迷失了答案,恐怕我离开他时会比起他时更加困惑.我想听听其他有关为什么这样做的解释.

I certainly know that this is valid code but, when I tried to explain it to him, I found myself stumbling over the answer and I'm afraid I left him more confused than when he started. I'd like to hear some other explanations of why this works.

有什么想法吗?为什么要在类本身的定义内实例化该类的实例?

Any thoughts? Why can you instantiate an instance of a class within the definition of the class, itself?

推荐答案

您正在编译时定义类,其所有字段和方法等.直到运行时才创建实例.因此,没有矛盾,您在到达第1行时就完全定义了该类.

You are defining the class, all its fields and methods etc at compile time. The instance is not created until runtime. So there is no contradiction, the class is fully defined by the time you reach line #1.

正如其他人指出的那样,由于 main 方法是 static ,因此您无需实例化对象即可到达第1行,但是您可以这样做而不会出现问题.我一直在使用这种模式进行一类实验.

As others point out, because the main method is static you will reach line #1 without having instantiated an object, but you can do so without issue. I use this pattern all the time for one-class experiments.

这篇关于为什么可以在其定义内实例化一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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