[英]Create a parameterized constructor
所以,我現在正在做我的家庭作業。 然而,我堅持了這個作業的幾個部分。
public class CheeseCake {
//Instance Variables
private double Cheese;
private int StrawBerry;
private double Cream;
public CheeseCake() {
Cheese = 0;
StrawBerry = 0;
Cream = 0;
}
//Constructor
public CheeseCake (double milk, int fresh, double temp)
{
Cheese = milk;
StrawBerry = fresh;
Cream = temp;
}
// (setter)
public void setCheese(double milk){
Cheese = milk;
}
public void setStrawBerry(int fresh){
StrawBerry = fresh;
}
public void setCream(double temp){
Cream = temp;
}
//(getter)
public double getCheese(){
return Cheese;
}
public int getStrawBerry(){
return StrawBerry;
}
public double getCream(){
return Cream;
}
{
}
//Method to display data, (need to work on this)
public void display() {
System.out.println(Cheese);
System.out.println(StrawBerry);
System.out.println(Cream);
System.out.println("You used " + Cheese + " g of Creamcheese to make Cheese");
System.out.println("You used " + StrawBerry + " StrawBerry to make StrawBerry CheeseCake");
System.out.println("You used " + Cream + " g of Cream to make Cream Cheese");
}
}
這是我的演示,它幫助我運行這個程序。
public class Demo {
public static void main(String[] args) {
CheeseCake cheesecake = new CheeseCake();
cheesecake.setCheese(5);
cheesecake.setStrawBerry(20);
cheesecake.setCream(10);
cheesecake.display();
}
}
所以,我的問題是我完成了創建 3 個實例方法和 getter、setter 方法。 另外,我創建了我的默認構造函數。 但我不確定如何創建參數化構造函數。 “創建一個參數化構造函數,將所有實例變量作為參數,並將實例變量設置為參數提供的值”
另外,我不確定我的老師希望我在演示方法中做什么。
創建一個名為 Demo.java 的類。 此類將包含您的主要方法,使用默認構造函數創建類的實例。 調用所有對象 set 方法為對象賦值 調用對象顯示方法,打印出它的值 使用參數化構造函數創建類的另一個實例 調用對象顯示方法,打印出它的值
我的演示方法對嗎? 或者我應該添加更多的東西。 另外,我應該添加更多構造函數來制作參數化構造函數嗎? 我不知道如何制作參數化構造函數。
默認構造函數不接受任何參數。 您的第二個構造函數是參數化構造函數。 而且您的代碼沒問題,您只需要創建一個更多參數化的復制構造函數,它將另一個實例作為參數。 IE
public CheeseCake (CheeseCake ck)
{
Cheese = ck.getCheese();
StrawBerry = ck.getStrawBerry();
Cream = ck.getCream();
}
現在您需要使用此構造函數在演示類中創建一個實例
CheeseCake cheesecake2 = new CheeseCake(cheesecake);//傳遞第一個對象作為參數
現在調用第二個對象的顯示方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.