Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Implicit Getters and Setters

User_B370JNov 15 2020

I was wondering why Java forces us to bother with the code clutter of explicit getters and setters, when a compiler modification could add them as needed to each class property in compliance with their access modifiers.
For example, we could have something like this:

public class State {
    public int property;
}

public class ExtendedState extends State {
    private int counter = 0;
    public int getProperty() {
        return property + ++counter;
    }
}

public class Client {
    public void doStuff() {
        State state = new State();
        state.setProperty(5);                     // implicit setter
        int stateValue = state.getProperty();     // implicit getter returns stateValue == 5
        State extendedState = new ExtendedState();
        extendedState.setProperty(5);
        stateValue = extendedState.getProperty(); // getter override returns == 6
    }
    
}

I'm thinking that there must be some good reason why this hasn't been implemented by now, but I can't think of one. No modification to the JVM would be required, so previously-compiled bytecode will still work. The set of code that will compile under this new specification is fully contained in the set of code that won't, so no issues exist with compiling legacy code. If someone has put a getter or setter on the class that is named as if it involves a property, but does something unrelated to it, the compiler will respect that and not overwrite what is specified in the code. Since the access modifiers of the getters and setters correspond to the access modifiers of the underlying properties, data encapsulation would be maintained. If for some reason, people object to it, it could even be implemented as an optional feature that is invoked with a compiler switch. There must be something I'm not thinking of here.
I looked into taking this question to the JCP, but it became immediately apparent that I'm not supposed to be wasting their time with half-baked ideas and intermediate-level questions, so I thought I was try here first.

This post has been answered by Roland Mueller on Nov 16 2020
Jump to Answer

Comments

Hi
Is this related to any particular livelabs workshops ? or a general issue related to Oracle Analytics Installation ?
regards, Madhusudhan Rao

1 - 1

Post Details

Added on Nov 15 2020
4 comments
1,467 views