Kobe-Wan Kenobi
Kobe-Wan Kenobi

Reputation: 3864

Private attributes in local class

Is there any use of having private attributes in (private) local class and have get(), set() methods?

 class a{
     private class b {
         private int att;
         public int getAtt(){
             return att;
         }
         public setAtt(int att){
             this.att = att;
         }
     }
 }

vs

  class a{
     private class b {
         public int att;
     }
 }

To me it makes sense that all attributes should be public, since they are used only in outer class anyway?

Upvotes: 1

Views: 365

Answers (5)

S-MILE-S
S-MILE-S

Reputation: 114

it expresses the Encapsulation . att is be protected in the b,b hide the details that how to set or get att.b only provides the method to external.

Upvotes: 1

rKatex
rKatex

Reputation: 117

It's not necessary to do that with getters and setters, if you want to access the fields in the surrounding class.

If you want to restrict the access from the surrounding class, it obviously makes sense to have getters and setters.

Upvotes: 0

OldCurmudgeon
OldCurmudgeon

Reputation: 65793

This is a common pattern for factories. The inner private class implements a public interface.

public interface IB {

    public int getAtt();

    public void setAtt(int att);

}

static class BFactory {

    public IB makeOne() {
        return new B();
    }

    private class B implements IB {

        private int att;

        public int getAtt() {
            return att;
        }

        public void setAtt(int att) {
            this.att = att;
        }
    }
}

Upvotes: 4

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

Also if the you expose them with getter and setter methods hiding internal representation can be important.

Now att is an attribute, but imagine that tomorrow it will be a calculated field. You don't need to change the external class, but only the implementation of setter and getter methods.

Additionally in the setter method you can make a validation of parameter before setting att.

Upvotes: 0

Florian
Florian

Reputation: 712

I guess that heavily depends on how you want to use your inner class. If it is only a container for access by the outer class, you can keep the attributes public and avoid getters/setters. Private attributes of the inner class are still useful though for attributes used only by methods in the inner class.

Upvotes: 0

Related Questions