Creating a Java Desktop Class with Encapsulation and RAM Upgrade
Write a Java program to create a class called Desktop with private instance variables brand, processor, and ramSize. Provide public getter and setter methods to access and modify these variables. Add a method called upgradeRam() that takes an integer value and increases the ramSize by that value.
Sample Solution:
Java Code:
Desktop.java
Main.java
Output:
Brand: ComputeMaster Processor: Intel Core i7 RAM Size: 64GB
Explanation:
- Private Instance Variables: The brand, processor, and ramSize variables are declared as private to ensure encapsulation.
- Public Getters and Setters: These methods provide controlled access to the private variables.
- getBrand(): Returns the brand.
- setBrand(String brand): Sets the brand.
- getProcessor(): Returns the processor.
- setProcessor(String processor): Sets the processor.
- getRamSize(): Returns the RAM size.
- setRamSize(int ramSize): Sets the RAM size.
- upgradeRam Method: Takes an integer value and increases the ramSize by that value if it's positive.
- Main Method: Tests the functionality of the Desktop class by creating an instance, setting its properties, upgrading the RAM, and printing the details.
Note on Encapsulation
Encapsulation works in the above exercise by:
- Hiding Data: The private instance variables brand, processor, and ramSize are not accessible directly from outside the class.
- Controlled Access: The public getter and setter methods provide controlled access to the private variables, allowing for validation and modification when necessary.
- Data Integrity: Encapsulation helps maintain data integrity by ensuring that the internal state of the object can only be changed through well-defined methods.
For more Practice: Solve these Related Problems:
- Write a Java program where the "Desktop" class prevents upgrading RAM beyond a limit.
- Write a Java program where the "Desktop" class includes a method to check system compatibility for software.
- Write a Java program where the "Desktop" class allows users to upgrade the processor only to supported models.
- Write a Java program where the "Desktop" class includes a method to estimate power consumption.
Go to:
Java Code Editor:
Improve this sample solution and post your code through Disqus
PREV : Creating a Java Smartphone Class with Encapsulation and Storage Increase.
NEXT : Creating a Java House Class with Encapsulation and Price Calculation.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.