WC - Accessor and Mutator Methods (Lesson)
Accessor and Mutator Methods
Introduction
Encapsulation allows data to be hidden to avoid it being accessed and manipulated by outside programs. We use encapsulation when we declare instance variables as private. Since they are private, they are only accessible within the class. This helps prevent them from being manipulated improperly. We can use accessor and mutator methods to safely access and change instance variables without destroying data or having negative side-effects.
View the video below:
Accessor and Mutator Methods
Click below to view the Accessor and Mutator Methods presentation.
Return Types
Click below to begin the Return Type Challenge Activity.
Circle Class
Add the accessor, mutator, and toString methods to the Circle class that you previously created. Compile your code to make sure there are no syntax errors. We will add more to this class in the next lesson. The accessor and mutator methods should access and change the radius instance variable. The toString method should return a String that states, “ This is a circle with radius, ___.” The radius should be filled in using the instance variable.
Practice-It! Practice
Go to the PracticeIt website
Links to an external site..
Log into account.
Click on Start Practicing!
Go to the most recent edition.
Click on Chapter 3: Parameters and Objects.
Complete Self-Check: 3.18
IMAGES CREATED BY GAVS