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: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).
Uttar Pradesh recorded the highest industrial growth rate during -
What is the primary aim of the 'Prithvi' program approved by the Union Cabinet?
Which country has approved the omicron vaccine recently?
Who has been awarded with the Royal Order of Merit of the United Kingdom?
At what age are children prohibited from employment in any factory, mines, or hazardous work in India?
Which of the following Panchayats in Uttar Pradesh is/are included in district planning?
1. Nagar Panchayat
2. Village Panchayat
3. Regional Panchayat
Consider the following statements-
Assertion (A) The loss of forest cover in India has been directly related to India's demographic transition.
Which is not a factor responsible for soil formation in given options?
What does the term 'Saharana' refer to in the context of the Sahariya Tribe?
What target has the government set to reduce accidental death by 2030?Â