Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getters/setters in Java

Tags:

I'm new to Java, but have some OOP experience with ActionScript 3, so I'm trying to migrate relying on stuff I know.

In ActionScript 3 you can create getters and setters using the get and set keywords, meaning you create a method in the class and access data through a property of an instance of that class. I might sound complicated, but it's not. Here's an example:

class Dummy{      private var _name:String;      public function Dummy(name:String=null){         this._name = name;     }      //getter     public function get name():String{         return _name;     }      //setter     public function set name(value:String):void{     //do some validation if necessary         _name = value;     }  } 

And I would access name in an object as:

var dummy:Dummy = new Dummy("fred"); trace(dummy.name);//prints: fred dummy.name = "lolo";//setter trace(dummy.name);//getter 

How would I do that in Java?

Just having some public fields is out of the question. I've noticed that there is this convention of using get and set in front of methods, which I'm OK with.

For example,

class Dummy{      String _name;      public void Dummy(){}      public void Dummy(String name){         _name = name;     }      public String getName(){         return _name;     }      public void setName(String name){         _name = name;     }  } 

Is there an equivalent of ActionScript 3 getter/setters in Java, as in accessing a private field as a field from an instance of the class, but having a method for implementing that internally in the class?

like image 795
George Profenza Avatar asked May 17 '09 17:05

George Profenza


Video Answer


2 Answers

Nope. AS3 getters and setters are an ECMAScript thing. In Java, you're stuck with the getVal() and setVal() style functions--there isn't any syntactic sugar to make things easy for you.

I think Eclipse can help auto-generating those types of things though...

like image 186
zenazn Avatar answered Sep 21 '22 17:09

zenazn


Your Java code is fine, except that you would, want to make _name private.

There are no get and set keywords in Java as in your AS3 example. Sorry, it doesn't get better than what you're doing already.

Corrected code:

class Dummy {   private String _name;    public void Dummy() {}    public void Dummy(String name) {     setName(name);   }    public String getName() {     return _name;   }    public void setName(String value) {     _name = value;   } } 
like image 42
Stephan202 Avatar answered Sep 19 '22 17:09

Stephan202