'new' 关键字在 Java 中的实际作用是什么,我应该避免创建新对象吗? [英] What does the 'new' keyword actually do in Java, and should I avoid creating new objects?

查看:33
本文介绍了'new' 关键字在 Java 中的实际作用是什么,我应该避免创建新对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不久前就注册了,不过自从我开始学习计算机编程以来,我一直在充分利用这个网站,我一直在自学并认为这是我的一个小爱好.

I signed up a few moments ago, though I've been making great use of this site since I took up computer programming, which I've been teaching myself and consider a little hobby of mine.

我确实查找过类似的问题,但实际上我找不到我想要的答案.现在,请注意,在 Java(这是我被建议开始使用的语言)中,根据需要声明和实例化变量被认为是良好的编程习惯,请考虑以下几行:

I did look up for similar questions, but in fact I couldn't find the answer I was seeking for. Now, being aware that, in Java (that's the language I was suggested to start off with), it is considered good programming practise to declare and instantiate variables as you need them, please consider the following lines:

class MyClass {
    void myMethod() {
        AnotherClass myObject = new AnotherClass();
        myObject.doStuff();
    }
}

现在,假设我在运行程序时调用 myMethod() 10 次,这是如何工作的?每次都会创建一个新对象吗?myObject 变量是否每次都重新分配?编译器是否会跳过类似的代码,因为它看到对象已经创建并且变量 myObject 已经分配给这样的对象?简而言之:仅当我打算只调用一次该方法时,我才应该编写这样的代码吗?我知道...问这样一个愚蠢的问题让我感到羞耻,但请给我一个机会!提前致谢!

Now, suppose I invoke myMethod(), say, 10 times while running my program, how does that work? Is a new object create every time? Is the myObject variable reallocated every time? Does the complier skip that like of code as it sees that the object has already been created and the variable myObject already been assigned to such object? In a nutshell: should I write code like that only if I plan to invoke that method only once? I know... shame on me for asking such a stupid question, but please give me a chance! Thanks in advance!

--------------------------- 已编辑 ---------------------

--------------------------- edited -----------------------------

那么现在我应该在得到新答案后编辑这篇文章吗?顺便说一句......天哪,太快了,非常感谢!哇,这让我很困惑,我想这是因为我一直在自学……无论如何,每次为 myObject 变量创建一个 new AnotherClass 对象不是没用吗?我的意思是,如果我想在整个程序中使用 myObject 变量,我不应该一劳永逸地声明它吗?也许在另一种方法中,我只会调用一次?因为据我所知,每次我调用 myMethod() 时都会创建一个新对象,从而覆盖 myObject 自己的属性,也就是变量,还是我在胡说八道?

So now am I supposed to edit this post after I get new answers? btw... gosh that was quick, thanks a lot! And wow that confused me, a lot, I guess that's due to the fact that I've been teaching myself so... Anyways, isn't it useless to create a new AnotherClass Object for the myObject variable every time? I mean, if i want to use the myObject variable throughout my program, shouldn't I declare it Once And For All? maybe in another method, that I'm going to invoke only once? Because as far as I understand, every time i invoke myMethod() a new object is creating, thus overriding myObject's own properties aka variables or am I just talking nonsense?

--------------------------- 已编辑 ---------------------

--------------------------- edited -----------------------------

从一些我现在不记得的网站上阅读这段代码后,我产生了疑问:

My doubts came after reading this code from some website I can't remember right now:

    public class DataBase {

    private static String buf, retString = "
";
    private static File file = new File("test.txt");

    public static void readText(JTextArea area) {   
        try {
            FileReader fr = new FileReader (file);
            BufferedReader br = new BufferedReader(fr);
            while ((buf = br.readLine()) != null) {
                area.append(buf); 
                area.append(retString);
            }
            br.close(); 
            fr.close();
        }
        catch (IOException e) {
            System.out.println("Exception: " + e);
        }
    }

    public static void writeText(JTextArea area) {
        try {
            FileWriter fw = new FileWriter (file);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(area.getText());
            bw.close(); 
            fw.close();
        }
        catch (IOException e) {
            System.out.println("Exception: " + e);
        }
    }
}

我的意思是,为什么不声明 FileWriter、FileReader、BufferedReader 和 BufferedWriter在班级的顶端,就像他们对其他变量所做的那样?为什么不在构造函数中初始化它们呢?为什么每次调用方法时都这样做,而不是使用相同的实例变量?

I mean, why not declare FileWriter, FileReader, BufferedReader and BufferedWriter at the top of the class as they did for the other variables? and why not initialise them as well maybe in the constructor? Why doing it every time the method is called rather than using maybe the same instance variable?

推荐答案

是的,如果您调用 myMethod() 10 次,它将创建 10 个唯一且独立的对象.

Yes, if you called myMethod() 10 times it will create 10 unique and separate objects.

new 关键字完全按照它在罐头上所说的那样做,它创建一个全新的对象,而不管一个对象是否已经存在.它创建一个新对象并将对该对象的引用填充到它所给定的变量中,覆盖变量持有的任何先前值(对象).

The new keyword does exactly what it says on the tin, it creates a brand new object, irrespective of whether one already exists. It creates a new object and stuffs the reference to that object inside the variable it has been given, overwriting any previous value (object) the variable held.

myObject 变量是否每次都重新分配?

Is the myObject variable reallocated every time?

再说一次,是的,每次调用该方法时,它都会重新分配一个新对象.一个有趣的注意事项是,当您在方法体内定义变量时,变量不会真正"重新分配,因此每次方法结束时,它都会删除在其范围内定义的变量.所以它实际上做的是创建 10 个单独的变量并分配 10 个单独的对象,尽管正如我所说,其他的应该已经被自动删除,这样它就不会使用任何额外的内存.

Again, yes it would be re-allocated with a new object every time the method was called. An interesting note about this would be that the variable wouldn't "really" be re-allocated as you are defining the variable within the method body itself, so every time the method ends it will remove the variables that were defined within its' scope. So what it actually does is create 10 individual variables and assign 10 individual objects, although as I said the others should have been removed automatically so it wouldn't use any additional memory.

简而言之:如果我打算只调用一次该方法,我应该编写这样的代码吗?

In a nutshell: should I write code like that only if I plan to invoke that method only once?

正如我所说,在上面的示例中,每个对象都将在方法执行结束时被销毁(假设您没有将对象引用分配给方法范围之外的变量),因此在您的示例中,您可以很高兴根据需要多次调用该方法,但每次都不会与之前的调用相关联.

Well as I said, in the example above each object would be destroyed at the end of method execution (assuming you didn't assign the object reference to a variable outside the scope of the method) so in your example you could happily call the method as many times as you wanted but each time would in no way be connected to the previous calls.

我意识到我的写作方式可能令人困惑,所以如果你想让我澄清任何事情,尽管问.

I realise my way of writing can be confusing, so if you want me to clarify anything just ask.

'为什么不像其他变量那样在类的顶部声明 FileWriter、FileReader、BufferedReader 和 BufferedWriter?'

'why not declare FileWriter, FileReader, BufferedReader and BufferedWriter at the top of the class as they did for the other variables?'

好的,我假设你明白这些变量实际上并没有被称为 FileWriterFileReaderBufferedReaderBufferedWriter,而是变量类型.它们的名称是 fwfrbrbw.如果你不明白我的意思就问吧.从现在开始,我将通过您所做的名称来引用变量,以使阅读更容易,毕竟 fw 无论如何都代表 FileWriter 所以不应该有太多的混淆.

Okay, I assume you understand that the variables are not actually called FileWriter, FileReader, BufferedReader, and BufferedWriter, but rather this is the variable type. Their names are fw, fr, br, and bw. If you don't understand what I mean just ask. From now on I will refer to the variables by the names you did to make reading more easy, afterall fw just stands for FileWriter anyway so there should not be too much confusion.

这个问题的关键隐藏在变量本身的名称中.注意它们如何以 ReaderWriter 结尾,这可以为我们提供有关它们用途的微妙线索.显然 FileWriterBufferedWriter 以某种方式处理输出.通过查看代码,我们发现我们的怀疑是正确的,并且除了在 writeText(JTextArea area) 方法之外,这些变量不会出现.因此,如果变量未在代码中的其他任何地方使用,那么在使用它们的方法中定义和初始化它们是合乎逻辑的,这不仅使代码更易于阅读,因为我们知道"了这些变量仅与该方法相关,但也具有在方法执行结束时删除这些变量的好处,从而不会留下只使用非常短暂的变量.根据这些规则,我们可以说 FileReaderBufferedReader 也是如此.

The key to this question is hidden within the names of the variables themselves. Notice how they either end in Reader or Writer this can give us a subtle clue about their uses. Clearly FileWriter and BufferedWriter are to do with output in some way. By looking over the code we see that our suspicions were right and that at no point other than within the writeText(JTextArea area) method do these variables appear. So if the variable aren't used anywhere else within the code it would make logical sense to define and initialise them within the method that they are used in, not only does it make the code easier to read because we then "know" those variables are only related to that method, but also has the benefit of those variables being removed at the end of method execution, thereby not leaving variables in existence that were only used very briefly. By these rules we can say the same is true of FileReader and BufferedReader.

观察这个关于变量作用域的例子.(看我在代码中添加的注释)

Observe this example about variable scope. (Look at the comments I added to the code)

public class DataBase {

private static String buf, retString = "
"; // buf & retString - created
private static File file = new File("test.txt"); // file - created

public static void readText(JTextArea area) {   
    try {
        FileReader fr = new FileReader (file); // fr (FileReader) - created
        BufferedReader br = new BufferedReader(fr); // br (BufferedReader) - created
        while ((buf = br.readLine()) != null) {
            area.append(buf); 
            area.append(retString);
        }
        br.close();
        fr.close();
    } // fr (FileReader & br (BufferedReader) - destroyed
    catch (IOException e) {
        System.out.println("Exception: " + e);
    }
}

public static void writeText(JTextArea area) {
    try {
        FileWriter fw = new FileWriter (file); // fw (FileWriter) - created
        BufferedWriter bw = new BufferedWriter(fw); // bw (BufferedWriter) - created
        bw.write(area.getText());
        bw.close(); 
        fw.close();
    } // fw & bw - destroyed
    catch (IOException e) {
        System.out.println("Exception: " + e);
    }
}
} // buf, retString and file - Still exist as long as the object exists

从这个例子中可以更清楚地了解为什么变量在方法中定义而不是作为实例变量并在构造函数中初始化.它允许更简洁的代码以及更具可读性.

From this example it becomes more clear as to why the variables are defined in the methods rather than as instance variables and initialised within the constructor. It allows for much cleaner code as well as being more readabe.

为什么每次调用方法时都这样做,而不是使用相同的实例变量?

Why doing it every time the method is called rather than using maybe the same instance variable?

这个问题与变量类型有关.我们无法为所有信息重用单个变量,因为类型需要不同.

Well this question has to do with variable types. We couldn't reuse a single variable for all the information as the types would have needed to be different.

如果我们从代码中取出所有变量

If we take all the variables from the code

private static String buf, retString = "
"; // valid
private static File file = new File("test.txt"); // valid

FileReader fr = new FileReader (file); // valid
BufferedReader br = new BufferedReader(fr); // valid
FileWriter fw = new FileWriter (file); // valid
BufferedWriter bw = new BufferedWriter(fw); // valid

现在我们知道我们不能将与变量类型不同的值放入该变量中,因此类似于

Now we know that we cannot place a value that is not of the same type as the variable into that variable so something like

FileReader fr = new BufferedReader(fr); // Is not valid!

因为类型根本不匹配.

有意义吗?

这篇关于'new' 关键字在 Java 中的实际作用是什么,我应该避免创建新对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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