我只是在学习Java中的OOP。我正试图从另一个构建器调用构造函数来输入消息。谢谢您的帮助。这是我的代码:
import java.util.Scanner;
class Sample {
private String User;
private int ID;
public Sample(String user) {
Scanner sc = new Scanner(System.in);
User = user;
ID = 0;
User = sc.nextLine();
ID = sc.nextInt();
}//CONSTRUCTOR
}//Sample
public class Sample_2 {
private Sample user1, user2, user3;
public Sample_2() {
user1 = new Sample(); //FROM HERE I WANT TO CALL THE OTHER CONSTRUCTOR ABOVE.
user2 = new Sample();
user3 = new Sample();
}//CONSTRUCTOR
public static void main(String args[]){
}//main
}//Sample_2
答案 0 :(得分:2)
Sample
没有默认构造函数(即没有参数),因此您需要添加一个,如下所示:
class Sample{
private String User;
private int ID;
public Sample() {
/* something */
}
public Sample(String user){
// ...
或使用带有String
参数的参数,如下所示:
public Sample_2(){
user1 = new Sample("some string");
// ...
对于某些阅读,请参阅构造函数上的tutorial