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; }}

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.
虎课网
虎课网是超过1800万用户信赖的自学平台,拥有海量设计、绘画、摄影、办公软件、职业技能等优质的高清教程视频,用户可以根据行业和兴趣爱好,自主选择学习内容,每天免费学习一个…
62 查看详情
以上就是今日课程:的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/366373.html
微信扫一扫
支付宝扫一扫