登录
推荐 文章 Go 技术 课程 下载 专题 AI
首页 >  文章 >  java教程

今日课程:

时间:2024-12-31 15:15:42 138浏览 收藏

golang学习网今天将给大家带来《今日课程:》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习文章或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

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.

到这里,我们也就讲完了《今日课程:》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>