📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    Consider the following Java code:     public

    class Product {         private String name;         private double price;         public Product(String name, double price) {             this.name = name;             this.price = price;         }         public String getName() {             return name;         }         public void setPrice(double newPrice) {             if (newPrice > 0) {                 this.price = newPrice;             } else {                 System.out.println("Price cannot be negative.");             }         }     }     This code demonstrates encapsulation by:
    A Using a constructor. Correct Answer Incorrect Answer
    B Having public methods. Correct Answer Incorrect Answer
    C Making name and price private and providing controlled access via getName() and setPrice(). Correct Answer Incorrect Answer
    D Not having a getPrice() method. Correct Answer Incorrect Answer
    E Allowing direct modification of name. Correct Answer Incorrect Answer

    Solution

    The key to encapsulation here is that name and price are private, meaning they cannot be directly accessed from outside the Product class. Instead, access is provided through public methods like getName() (a getter) and setPrice() (a setter), which includes validation logic (newPrice > 0).

    Practice Next
    ask-question