Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+20 votes
asked in CSC305 Fall 2022 by (8 points)

4 Answers

+12 votes

For example, You have a Car class and Engine Class. You creating an Engine object in Car class and using Engine Class's methods and fields within the Car class will be the example of Encapsulation.

In more details:
Let's say that Engine class has fields of its type and name.
Creating an Engine object in a Car class and setting the Engine object's type and name value with Engine class's methods and fields inside of Car class would be an example of encapsulation. Same thing can go for Wheel class, Headlight class, etc

answered by (8 points)
+12 votes

Encapsulation is to hide the implementation details from users. we should think about making our instance variables private. We should then have getter and setter methods in the class to set and get the values of the fields.

An example of encapsulation is the class of java.util.Hashtable. The user only knows that he can store data in the form of key/value pair in a Hashtable and that he can retrieve that data in various ways. But the actual implementation, like how and where this data is stored, is hidden from the user.

answered by (8 points)
+11 votes

Encapsulation also allows the program to use the same implementation if the hidden parts are changed.

For example, TVs used to be made with tubes and fluorescent screens, today they're made out of plastics and chemicals and motherboards. But the buttons we press to turn on the TV are still the same. We as the user of the TV don't need to know why or how the buttons work, just that they do.

Just like for our programs, we don't really need to know how the math behind scaling of the square tiles work, we just need to know that if we want to make the squares bigger, we access the zoom method. If the math or implementation of the zoom method changes, that shouldn't affect the fact that to change the scale, we still call the zoom method.

answered by (508 points)
–4 votes

You can read about Encapsulation here: https://www.w3schools.com/java/java_encapsulation.asp

answered by (8 points)
...