From the course: Java Object-Oriented Programming

Unlock the full course today

Join today to access over 23,200 courses taught by industry experts.

Implementing encapsulation with access modifiers

Implementing encapsulation with access modifiers - Java Tutorial

From the course: Java Object-Oriented Programming

Implementing encapsulation with access modifiers

- [Narrator] With encapsulation we want to make data hidden from other classes so they cannot use it directly. However, we still want it to be accessible indirectly through a clear pathway. in Java, one way we can achieve encapsulation for our attributes is to declare each attribute as private then write public methods to get and set the value of each attribute. With this, other classes will still be able to access the hidden data, but they can only do so through a public method of a given class. Let's continue working with our tree class and create three public methods that retrieve each attribute value. To make the first, we'll write public, double for the return type and we'll have it be getHeightFt and this will retrieve the height feet attribute. We'll also create a method for the trunk diameter then as we type it in, you'll notice our IDE comes up with some code completion. And it fills in the code for us…

Contents