Deepak Ananth
Deepak Ananth

Reputation: 1

Protected methods in Java

Why do we need protected modifier methods when we can directly set the variable to protected?

For e.g: In the below code, they set the instance variable SocialSecurityNumber to private and define a protected setter method to set its value? Why can't we directly set the variable SocialSecurityNumber to protected?

public class SSNWrapper {

    private int SocialSecurityNumber ;

    public SSNWrapper (int ssn) { socialSecurityNumber = ssn ;}
    public int getSSN () { return SocialSecurityNumber; }
    protected void setSSN(int SSN) { socialSecuritynumber = ssn ; }

}

Upvotes: 0

Views: 2412

Answers (3)

nosbor
nosbor

Reputation: 3009

Because sometimes you need to change operation which get or set this value. For example you need to calculate this value. Or set another value. Or run listener or something.... So this is to give you more flexibility.

Upvotes: 0

Woot4Moo
Woot4Moo

Reputation: 24336

From the tutorial on Access modifiers:

Tips on Choosing an Access Level:

If other programmers use your class, you want to ensure that errors from misuse cannot happen. Access levels can help you do this.

Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.

Avoid public fields except for constants. (Many of the examples in the tutorial use public fields. This may help to illustrate some points concisely, but is not recommended for production code.) Public fields tend to link you to a particular implementation and limit your flexibility in changing your code.

The short version is it prevents other classes from modifying the data within the class that declares the instance variable private.

Upvotes: 1

Mat
Mat

Reputation: 206899

In that specific example, there would not be much difference. In real life, the setSSN method should probably be more like:

protected void setSSN(int SSN) throws InvalidSSNException {
  // check that the given SSN is valid
  // ...
  socialSecurityNumber = ssn;
}

This allows the base class to guarantee that it only holds valid SSNs. The base class cannot guarantee that if the field is protected.

Upvotes: 3

Related Questions