Getters/setters in Java

后端 未结 7 1816
轻奢々
轻奢々 2021-02-18 13:18

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 sette

相关标签:
7条回答
  • 2021-02-18 13:55

    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...

    0 讨论(0)
  • 2021-02-18 13:55

    An IDE-independent way is to use Lombok, an annotation-based library that generates getters, setters, and even equals() and hashcode(). It does this for the compiler, but not in the source file, so you don't have to look at the methods, just use them.

    0 讨论(0)
  • 2021-02-18 13:58

    Sadly, no, there isn't the equivalent language-level support in java.

    The get* and set* patterns though are so established in java culture that you'll find strong IDE support for them (e.g., eclipse will make them for you automatically), and if you're working in something that uses the expression language first made for jsps (EL), then you'll be able to use the property notation to access getters and setters.

    0 讨论(0)
  • 2021-02-18 14:04

    In Java, the only option you have without exposing the internals of your object is to make your own getters and setters as you have in your example.

    The convention is to prepend get or set in front of the field which is being altered. So, as in your example, the field name would have getName and setName methods as their corresponding getter and setter, respectively.

    0 讨论(0)
  • 2021-02-18 14:06

    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;
      }
    }
    
    0 讨论(0)
  • 2021-02-18 14:08

    I would consider not having the getter or setter as they don't do anything in your case except make the code more complicated. Here is an example without getters or setters.

    class Dummy {
      public String name;
      public Dummy(String name) { this.name = name; }
    }
    
    Dummy dummy = new Dummy("fred");
    System.out.println(dummy.name);//getter, prints: fred
    dummy.name = "lolo";//setter
    System.out.println(dummy.name);//getter, prints: lolo
    

    IMHO Don't make things more complicated than you need to. It so often the case that adding complexity will suffer from You-Aint-Gonna-Need-It

    0 讨论(0)
提交回复
热议问题