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.
以上就是今日课程:的详细内容,更多请关注慧达安全导航其它相关文章!
免责 声明
1、本网站名称:慧达安全导航
2、本站永久网址:https//www.huida178.com/
3、本站所有资源来源于网友投稿和高价购买,所有资源仅对编程人员及源代码爱好者开放下载做参考和研究及学习,本站不提供任何技术服务!
4、本站所有资源的属示图片和信息不代表本站的立场!本站只是储蓄平台及搬运
5、下载者禁止在服务器和虚拟机下进行搭建运营,本站所有资源不支持联网运行!只允许调试,参考和研究!!!!
6、未经原版权作者许可禁止用于任何商业环境,任何人不得擅作它用,下载者不得用于违反国家法律,否则发生的一切法律后果自行承担!
7、为尊重作者版权,请在下载24小时内删除!请购买原版授权作品,支持你喜欢的作者,谢谢!
8.若资源侵犯了您的合法权益,请持 您的版权证书和相关原作品信息来信通知我们!QQ:1247526623我们会及时删除,给您带来的不便,我们深表歉意!
9、如下载链接失效、广告或者压缩包问题请联系站长处理
10、如果你也有好源码或者教程,可以发布到网站,分享有金币奖励和额外收入!
11、本站资源售价只是赞助,收取费用仅维持本站的日常运营所需
12、因源码具有可复制性,一经赞助,不得以任何形式退款。
13、本文内容由网友自发贡献和站长收集,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系1247526623@qq.com
发表评论 取消回复