简体   繁体   English

如何在另一个方法的类中调用构造函数

[英]How to call a constructor within the class in another method

I'm a student. 我是学生。 Just got back a homework assignment stating I should call the constructor method rather than reusing the same code. 刚回来做作业,说我应该调用构造函数方法,而不是重用相同的代码。 I copied the code because I could not call the constructor without an error. 我复制了代码,因为我无法在没有错误的情况下调用构造函数。 What is the proper syntax to call the constructor method...from a separate method? 从单独的方法调用构造函数方法的正确语法是什么?

I did do a search, but I could not find this specific (within the class) issue. 我确实做了搜索,但是找不到这个特定的问题(在班级内)。 I did try using "this" as well as creating a class instance too, but I keep getting errors. 我确实尝试过使用“ this”以及创建类实例,但是我一直在出错。

import java.util.Random;
public class Coin {

    // variable for a generic coin toss
    private String sideUp;  

    // Constructor 

    // ******************** Instructor notes...
    // This is the same code as your toss() method
    // It is OK to call that method from your constructor.
    // Don't copy/paste code or repeat yourself if not required.
    public Coin() { 
        Random rand1 = new Random();
        int x = rand1.nextInt(2);   
        if (x > 0){
            sideUp = "Heads";
        }else{
            sideUp = "Tails";
        }
    }


    //Void Method
    public void toss() {
        // how to call the Coin constructor above??????????????????????????
        Coin();
    } 
}

Do it the other way around. 反之亦然。 Move the code back to your toss method and just call toss() from inside the constructor. 将代码移回toss方法,只需从构造函数内部调用toss()

import java.util.Random;
public class Coin {

   // variable for a generic coin toss
   private String sideUp;  

   // Constructor 

   // ******************** Instructor notes...
   // This is the same code as your toss() method
   // It is OK to call that method from your constructor.
   // Don't copy/paste code or repeat yourself if not required.
   public Coin() { 
       toss();  
   }


   //Void Method
   public final void toss() {
       Random rand1 = new Random();
       int x = rand1.nextInt(2);   
       if (x > 0){
           sideUp = "Heads";
       }else{
           sideUp = "Tails";
       }
   } 
}

As is pointed out in other comments and answers, calling methods that may be overriden from a constructor is a bad idea. 正如其他评论和答案所指出的那样,可能从构造函数中覆盖的调用方法是一个坏主意。 Here's a good explanation for why that is: Why is it considered bad practice to call a method from within a constructor? 这是为什么的一个很好的解释: 为什么在构造函数中调用方法被认为是不好的做法?

You can make the method final as I did here to avoid the problems. 您可以像我在此处那样将方法finalfinal方法,以避免出现问题。

To use a constructor you need to use the 'new' keyword. 要使用构造函数,您需要使用'new'关键字。 eg 例如

Coin myCoin = new Coin();
 // ******************** Instructor notes... // This is the same code as your toss() method // It is OK to call that method from your constructor. 

I'm afraid the 3rd statement is not really true. 恐怕第三句话不是真的。 It is actually not ok to call an overridable method in your constructor. 实际上,在构造函数中调用可重写方法是不可行的 That will leak the this reference before the object has been fully initialized. 在对象完全初始化之前,这将泄漏this引用。 That could give you unexpected result , if you override your method in subclass. 如果您覆盖子类中的方法,则可能会给您带来意想不到的结果 You should confirm this with your instructor. 您应该与您的教练确认。

BTW, the instructor doesn't says to call constructor from method, but the other way round. 顺便说一句,讲师不是说要从方法中调用构造函数,而是相反。 But you wouldn't do either of them. 但是您不会做任何一个。 Just move the code from constructor to the toss() method, if that part of code has to be the part of toss() method. 刚刚从构造函数中的代码移到toss()方法,如果代码部分必须是部分toss()方法。

Or if you really want those codes to be executed both in constructor and toss() method, then create a private method in your class, move those codes there, and call it from both the places: 或者,如果您确实希望同时在构造函数和toss()方法中执行这些代码,则在您的类中创建一个private方法,将这些代码移到那里,然后从两个地方调用它:

public class Coin {

    // variable for a generic coin toss
    private String sideUp;  

    public Coin() {
        initSideUp();
    }

    //Void Method
    public void toss() {
        initSideUp();
    }

    private void initSideUp() { 
        Random rand1 = new Random();
        int x = rand1.nextInt(2);   
        if (x > 0){
            sideUp = "Heads";
        }else{
            sideUp = "Tails";
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM