thox
thox

Reputation: 159

Is making an instance variable private only benefits the subclasses?

I'm a beginner. I'm currently learning about OOP. From what I understand, making instance variables private means it is accessible within the class only. So you need to make set and get methods to have access into it for subclasses.

But I can directly change the private instance variable within the class it is belonged right? Then this leads me to the question.

Upvotes: 0

Views: 51

Answers (1)

Tyler
Tyler

Reputation: 986

The purpose of using private variables with a getter and/or a setting to control how and who can interact with that variable.

A private variable inside a class can only be accessed within the class. That means that anything outside of the class can not be read or write to that variable.

By providing an public getter you are giving everything the ability to read that property.

By providing an public setter you are giving everything the ability to change that property.

You can change the access modifier on the getter and setter to control who can read or change the variable. You can also completely leave out a getter or setter to make variable read-only or write-only from outside the class.

If you are unfamiliar with access modifiers, I highly recommend reading up them. The most common ones when learning are public and private. Public basically means everything can see it, and private has already been discussed.

In addition to all the above, you can add additional functionality in your getter or setter. For example, you can validate input when someone uses the setter to ensure that certain rules are maintained.

E.X: If you have a variable of type string that is post to hold a 9 digit number. With the setter, you can make sure whatever is passed in is a valid number and has a specific length. If not, you can prevent the value from going through... Usually by throwing an exception.

The benefits are wide-spread and not limited to sub-classes. Don't really think about the benefit being to a particular class or object; but, rather the benefit is giving you, the programmer, more control over how others interact with your class.

Upvotes: 1

Related Questions