Home » Online Computer Education » Learn Fundamentals of Java Programming “Getter and Setter Methods in Java Programming ” Lesson 21

Learn Fundamentals of Java Programming “Getter and Setter Methods in Java Programming ” Lesson 21

Getter and Setter Methods

Private data members of a class cannot be accessed outside the class however, you can give controlled access to data members outside the class through getter and setter methods. A getter method returns the value of a data member. For example we could define a getter method in the Book class for the price data member as given below:

double getPrice() {
return price;
}

Similarly, we define a setter method but control how the price is set. We do not allow a book price to become lower than 100.0.

void setPrice(double newprice) {

if (newprice < 100)

System.out.println(“Price cannot be set lower than 100!”);
elses
price = newprice;
}

In the BookTest class, the getter and setter methods can be used to retrieve and set a new price for a book (Figure 1.8i). Let’s say the BookTest class wants to discount the price of the book1 object by 20%, we first get the book’s price using the getPrice() method, use the price to determine a discounted price for the book, and then use the setPrice() method to change the price of the book. The code for the same is as below:

double bookprice = book1.getPrice ();
bookprice = – 20*bookprice/100;
book1.setPrice (bookprice);

Now book1’s data member price is set to 360.0 (Figure 1.8j). However if a discount caused a book object’s price to fall below 100, the setter method would not change the price. Without a controlled setter function, the BookTest class could have changed the book’s price arbitrarily.

Java fundamentals  array  12

About

The main objective of this website is to provide quality study material to all students (from 1st to 12th class of any board) irrespective of their background as our motto is “Education for Everyone”. It is also a very good platform for teachers who want to share their valuable knowledge.

Leave a Reply

Your email address will not be published. Required fields are marked *