Question

Does anyone know if there is a plan to add in implicit getters and setters for Class variables?

I'm thinking of the current Scala code that allows this already. Something like the following, where if you don't define a getter/setter it uses the value, but if you do define a getter/setter for the value it uses that instead of a direct variable call.

class A{
    int value = 3;
}

class B{
    int value = 3;
    public int value(){
        return value;
    }
}

// in some method
A a = new A();
System.out.println(a.value); 
B b = new B();
System.out.println(b.value); // <-- no () for accessing value even though it uses the getter
Was it helpful?

Solution

not Java per se, but there is this Project Lombok

OTHER TIPS

Foreword: maybe I'm wrong but the question is maybe a better fit for java platform user/devel lists, like those at http://www.oracle.com/technetwork/java/javase/community/index.html

I suppose you'll receive more meaningful answers there, and less speculation.

My own take on the subject is that the JavaBean model is far too established to admit any significant change for backward compatibility, and that java encapsulation model is based on the concept that you hide fields with private access and provide accessors/mutators.

If you only want to expose members you can simply make them public.

Translating fields to automatic accessor/mutator methods is quite a big change to the language, and would probably create much confusion for little gain.

You should also consider that the scala choice implies a radically different approach to member access, for the sake of uniform access principle.

A simple getter returns a field value. However a getter can also return the results of an operation:

public boolean isError()
{
   return errorList.size() > 0;
}

Similarly a setter might do other operations:

public void setName(String name)
{
   this.name = name;
   this.sortName = name.toLowerCase();
}

So other than the bean paradigm, and for the sake of consistency, getters/setters should be used rather than direct field access.

Java 14 (LTS release) has records, but you need to compile with additional options for it to work. Records provide getters for the constructor params and aim to solve a few other problems inherent in earlier versions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top