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.
B Having public methods.
C Making name and price private and providing controlled access via getName() and setPrice().
D Not having a getPrice() method.
E Allowing direct modification of name.
Practice Next

Hey! Ask a query