views:

187

answers:

4

C# properties (I mean get and set methods) are a very useful feature. does java have something similar to C# properties too. I mean how we can implement something like the following C# code in java:

public string Name
{
    get
    {
        return name;
    }

    set
    {
        name = value;
    }
}

thank you in advance

+10  A: 

No, Java does not have the equivalence. It only has accessor and mutator methods, fancy names for getter and setter methods. For example:

public class User {
    private String name;

    public String getName() { return this.name; }
    public void setName(String name) { this.name = name; }
}
Khnle
It should be clear that these getter/setter methods are not separate constructs with flashy syntax like properties are in C#. Instead, they are just ordinary methods that we happen to name getName() and setName() and task them with acting as properties by convention rather than through dedicated language constructs.
filip-fku
True, getName() are setName() are so-named purely by convention. One could just decide to name these methods as, for example, retrieveUserName() and assignUserName(), and that would be just OK. This kind of convention is idiomatic in Java and tools like Eclipse IDE follow.
Khnle
It's not **just** a convention. There is a specification to go along with Java Beans and an API that makes them useful. http://java.sun.com/javase/technologies/desktop/javabeans/docs/spec.html
Chris Nava
+3  A: 

You can just declare a private variable, and write the methods by hand. However, if you are using Eclipse, you can click on a variable, select "Source" and "Generate getters and setters." This is about as convenient as C# properties.

Larry Watanabe
+7  A: 

You could have a look at Project Lombok as it tries to take the pain out of writing boiler plate Java code. It allows you to either use @Getter and @Setter annotations, which will provide getBlah() and setBlah() methods:

public class GetterSetterExample {
  @Getter @Setter private int age = 10;
}

Or you can just use @Data and it will automatically implement your hashCode(), equals(), toString() and getter methods, along with setters on non-final fields:

@Data public class DataExample {
  private String name;
}

Problems I have found with the project, however, are that it's all a bit voodoo, which can be off-putting, and that you have to install an eclipse (or what ever) plugin to get auto compilation to work.

Ben Smith
And a further problem is that if you use Lombok, then you're no longer writing portable Java code.
Neal Gafter
+2  A: 

There has been a proposal to add C#-like support for properties (and events) to Java, but it looks like this is rejected for the next version of Java (Java 7).

See:

Jesper