![](/img/trans.png)
[英]Instantiate a Scala class from Java, and use the default parameters of the constructor
[英]Ignore default constructor and use constructor with parameters in Java
我對Java的了解不是很好,這就是為什么我要問這個聽起來很愚蠢的問題。 盡管如此,我試圖找出如何忽略類的默認構造方法,而使用帶有參數的構造方法。 例如,如下所示:
public class Name {
String firstName, lastName;
public Name()
{
String dialog = JOptionPane.showInputDialog("First and Last name: ");
Scanner inName = new Scanner(dialog);
firstName = inName.next();
lastName = inName.nextLine();
}
public Name(String newFirst, String newLast)
{
firstName = newFirst;
lastName = newLast;
}
}
然后,我有一個名為Student的類,它像這樣擴展名稱:
public class Student extends Name
{
public Student(String firstName, String lastName)
{
firstName = firstName;
lastName = lastName;
}
}
因此,Name類的第一個構造方法提示用戶輸入其名稱,但是說我已經知道用戶的名稱並將其存儲在某些變量中,如何創建新的Student()對象(實際上是名稱( )對象),而無需調用第一個默認構造函數,而是這樣調用它:
Student student1 = new Student(firstName, lastName);
我知道為什么以下行會調用默認的構造方法:
Student student1 = new Student();
但是,即使我正在使用參數,下一行stil也會調用相同的無參數構造方法:
Student student1 = new Student(firstName, lastName);
我在這里做錯了什么?
第一:在構造函數中使用掃描器從外部世界獲取輸入是一個可怕的想法。
其次:Student中的構造函數調用Name中的構造函數,該構造函數不帶任何參數,因為沒有顯式調用super()。 如果要避免這種情況:
public Student(String firstName, String lastName)
{
super(firstName, lastName);
}
如果您沒有從子類中顯式調用超級構造函數,它將隱式調用不帶參數的超級構造函數。
更清楚地說,當你寫
public Student(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
您實際上在做:
public Student(String firstName, String lastName)
{
super();
this.firstName = firstName;
this.lastName = lastName;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.