3

In C#, I Can use a simple way like below

public class Dummy 
{
   public string Name { get; set; }
}

but if i use java to do the same thing, i must do like below

public class Dummy {
    private String _name;

    public void setName(String value) {
        this._name = value;
    }

    public String getName() {
        return this._name;
    }
}

so, you can tell that is at least 7 line codes take the same efftects as 1 line code in c#; so, i'm wondering at is there a simple way in java that i can use to simple set field or get field?

thx for advanced

user2864740
  • 60,010
  • 15
  • 145
  • 220
TechStone
  • 141
  • 6

3 Answers3

3

Java does not support that particular C# idiom, however many IDEs include methods to generate accessors and mutators; for example, in eclipse you can select

Source, Generate Getters and Setters

or

SHIFT-ALT-s   r

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

There's nothing built-in to the language, but you could always use Project Lombok's annotation set to generate getters and setters for you at compile-time.

In particular, @Data is quite powerful - it generates your getter, setter, and a toString() method.

Here's an example:

import lombok.Data;

@Data
public class Node<T extends Comparable<T>> {

    private final T data;
    private Node<T> left = null;
    private Node<T> right = null;

    public Node(final T theData) {
        data = theData;
    }

    public void add(final Node<T> theNode) {
        if(data.compareTo(theNode.getData()) <= 0) {
            // goes to the left
            left = theNode;
        } else {
            // goes to the right
            right = theNode;
        }
    }
}

You may have to install a plugin for your IDE to recognize that this is being generated at compile-time, but this takes care of all of your setter and getter boilerplate code.

Makoto
  • 104,088
  • 27
  • 192
  • 230
0

That's is language specific, you cannot expect any more.
There is a simpler way to create get/set just by some clicking:
On eclipse editor, right click to open menu\Source\Generate Getters and Setters
-> select property that's you want to getter and setter.

tana
  • 585
  • 1
  • 5
  • 16