<code class="java">class Supermarket {
private int price; // Instance variables, using private for better encapsulation
private int discount;
private String productName;
// Parameterized constructors
public Supermarket(String productName, int price, int discount) {
this.price = price;
this.discount = discount;
this.productName = productName;
}
public Supermarket(String productName, int price) {
this.price = price;
this.productName = productName;
this.discount = 0; // Default discount if not provided
}
public static void main(String[] args) {
Supermarket product1 = new Supermarket("Good Day", 10, 2);
Supermarket product2 = new Supermarket("Rice", 55);
System.out.println(product1.getProductName()); // Accessing using getter method
System.out.println(product2.getProductName());
product1.buy();
product1.returnProduct();
}
// Methods for better readability and maintainability
public void buy() {
System.out.println("Buying " + productName + " for " + (price - discount));
}
public void returnProduct() {
System.out.println("Returning " + productName + " for " + price);
}
// Getter method for productName
public String getProductName() {
return productName;
}
}</code>
The improved code uses private instance variables (price, discount, productName) for better encapsulation, preventing direct access and modification from outside the class. It also introduces getter methods (like getProductName()) for controlled access to the instance variables. The names of the methods have been made more descriptive (e.g., return_product changed to returnProduct). Finally, a default discount of 0 is set in the constructor that takes only the product name and price. This makes the code more robust and easier to understand and maintain.
以上就是今日课程:的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号