[英]Error while creating object using parameterized constructor in Java
I'm getting below error when creating object along with parameterized constructor. 与参数化构造函数一起创建对象时,出现以下错误。
Main.java:6: error: constructor Cipher in class Cipher cannot be applied to given types
Main.java:6:错误:类Cipher中的构造函数Cipher无法应用于给定类型
Cipher cy = new Cipher(k); ^
required: no arguments 必需:无参数
found: int 找到:int
reason: actual and formal argument lists differ in length 原因:实际和正式论点清单的长度不同
Here is my files looks like 这是我的文件看起来像
<b>Main.java</b>
public class Main {
public static void main(String []args){
int k=8;
Cipher cy = new Cipher(k);
String encrypted_msg = cy.encrypt(message);
String decrypted_msg = cy.decrypt(encrypted_msg);
view1.displayResult("Decrypted message: "+decrypted_msg);
}
}
<b>Cipher.java</b>
import java.util.*;
public class Cipher
{
private int key;
// Constructor
public void Cipher(int k)
{
key = k;
}// end Constructor
} // end class
Change 更改
public void Cipher(int k)
to 至
public Cipher(int k)
With a return type of void
, that is not a constructor. 返回类型为
void
,则不是构造函数。 In Java, a constructor does not specify a return type. 在Java中,构造函数不指定返回类型。 The return type is simply the name of the class.
返回类型只是类的名称。
So in your example, because you have not defined a constructor, Java will provide a default no-argument constructor of the following format: 因此,在您的示例中,由于尚未定义构造函数,因此Java将提供以下格式的默认无参数构造函数:
public Cipher() {}
thus the error message is telling you that only a no-argument constructor exists, but you are calling a constructor that expects an int
argument. 因此,错误消息告诉您只有无参数的构造函数存在,但是您正在调用需要
int
参数的构造函数。
<b>Cipher.java</b>
import java.util.*;
public class Cipher
{
private int key;
public Cipher(int k) //remove the void
{
this.key = k; //use this for object level reference
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.