简体   繁体   English

从另一个构造函数和非法参数异常中调用构造函数

[英]Calling constructor from another constructor and illegal argument exception

for my two parameter constructor to call the four parameter constructor is it proper with what I have done(I am still learning). 为我的两个参数构造函数调用四个参数构造函数是否适合我所做的事情(我仍在学习)。 Also it is supposed to instantiate open interval so is that still correct? 还应该实例化打开间隔,这样仍然正确吗? for the copy constructor how would I make a copy of the explicit value constructor? 对于复制构造函数,我将如何复制显式值构造函数? Also how do I throw an exception if memory has not been allocated for object being copied? 另外,如果没有为要复制的对象分配内存,该如何引发异常?

for the copy constructor how would I make a copy of the explicit value constructor? 对于复制构造函数,我将如何复制显式值构造函数?

There is no built-in in Java for this. Java没有内置的功能。 You'd have to manually copy the fields you want to copy 您必须手动复制要复制的字段

public LetsCallThisClassInterval(LetsCallThisClassInterval other){
    this(other.left, other.right, other.stuff)
}

But this class looks like it should be immutable, so there is no real need for a copy constructor. 但是此类看起来应该是不可变的,因此实际上不需要复制构造函数。

Also how do I throw an exception if memory has not been allocated for object being copied? 另外,如果没有为要复制的对象分配内存,该如何引发异常?

That just does not happen in Java. 这只是在Java中不会发生。 Memory is managed for you, and if you get an object reference, it will have been properly allocated already. 内存是为您管理的,如果您获得对象引用,则它已经被正确分配了。

Or are you talking about other being null in the above example? 还是在上面的示例中谈论othernull In that case, you will get a NullPointerException automatically. 在这种情况下,您将自动获得NullPointerException If you prefer an IllegalArgumentException (debatable), you can add a null check: 如果您喜欢IllegalArgumentException (有争议),则可以添加一个空检查:

if (other == null) 
  throw new IllegalArgumentException("other interval cannot be null");

Let me see if I get this right, you want to do a constructor inception? 让我看看我是否做对了,您想做一个构造函数的开始吗? In this case what you would want to do is use the Constructor(//insert the variables that correspond); 在这种情况下,您要使用的是Constructor(//插入相应的变量); that should fix the problem. 应该可以解决问题。

Using "this" will make the constructor refer to itself, I mean the same method. 使用“ this”将使构造函数引用自身,我的意思是相同的方法。 For example it would be. 例如,它将是。

public Constructor(char leftsym, double left, double right, char rightsymb){
     new Constructor(left, right);
}

Now as a side note, the Constructor class already exists between the core classes in Java, I suggest that if you want to simplify your life change your java class name such as Constructor_1 or something like that. 现在作为一个补充说明,Java中的核心类之间已经存在Constructor类,我建议,如果您想简化生活,请更改Java类名,例如Constructor_1或类似的名称。

Good Luck 祝好运

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

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