这是我创建和管理对象时的主程序。
public class ShoppingCartManager {
public static void main(String[] args) {
//when declaring the object it's not changing the values.
ShoppingCart cart1 = new ShoppingCart("John Doe", "February 1, 2016");
System.out.println(cart1.getCustomerName());
}
}//end of class
////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////
这是类,构造函数应该写入类的私有变量,但它们不会更新。
import java.util.ArrayList;
public class ShoppingCart {
private String customerName = "none";
private String currentDate = "January 1, 2016";
//ArrayList<ItemToPurchase> cartItems = new ArrayList<ItemToPurchase>();
//constructor methods
//this is constructer that it calls
ShoppingCart(String Name, String Date) {
//Parameterized constructor which takes the customer name and date as parameters
String customerName = Name;
String currentDate = Date;
}
ShoppingCart() {
//String customerName - Initialized in default constructor to "none"
//String currentDate - Initialized in default constructor to "January 1, 2016"
String customerName = "none";
String currentDate = "January 1, 2016";
}
ShoppingCart(String Name) {
String customerName = Name;
}
/////////////////////////////////////////////////////
//Getter methods
//getCustomerName
public String getCustomerName(){
return customerName;
}
//getDate
public String getDate() {
return currentDate;
}
/////////////////////////////////////////////////////
}//end of class
我尝试重新构建构造函数并创建新对象。但对象 customerName 变量将始终保持默认的“none”。
public class ShoppingCart {
private String customerName = "none";
private String currentDate = "January 1, 2016";
//ArrayList<ItemToPurchase> cartItems = new ArrayList<ItemToPurchase>();
// Parameterized constructor
ShoppingCart(String name, String date) {
this.customerName = name; // Assign the parameter to the class field
this.currentDate = date; // Assign the parameter to the class field
}
// Default constructor
ShoppingCart() {
// The class fields are already initialized with default values, so you could leave this empty or remove it if you don't need to do anything else.
}
ShoppingCart(String name) {
this.customerName = name; // Assign the parameter to the class field
// currentDate will retain its default value unless explicitly set
}
// Getter methods
public String getCustomerName() {
return customerName;
}
public String getDate() {
return currentDate;
}
您在 ShoppingCart 类中遇到的问题源于您在构造函数中处理赋值的方式。当您在构造函数内为 customerName 和 currentDate 赋值时,您实际上是在创建局部变量并将值赋值给局部变量,而不是更新类字段。这就是为什么您的 customerName 始终保持默认值“none”。要解决此问题,您应该在设置值时删除构造函数内的数据类型声明。这样,您可以确保将提供的值分配给类的字段而不是新的局部变量。这应该有效。