本文介绍了在Java的getter / setter方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Java,但使用ActionScript 3的一些OOP的经验,所以我想迁移依靠的东西,我知道了。

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

在ActionScript 3中,您可以创建使用get getter和setter方法​​,并设置关键词,这意味着你通过这个类的一个实例的属性在类中创建和访问数据的方法。我可能听起来有点复杂,但它不是。这里有一个例子:

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

我将如何做到这一点在Java中?

How would I do that in Java?

只要有一些公共领域,是出了问题。我注意到,有使用GET了这一公约和方法,而我与确定前设置。

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.

例如,

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;
    }

}

有没有ActionScript 3的的getter / setter方法​​的Java中的等价物,如从类的实例访问私有字段作为一个领域,但其在类实现了内部的方法?

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

推荐答案

都能跟得上。 AS3 getter和setter是一种ECMAScript的事情。在Java中,你坚持的getVal()和SETVAL()风格的功能 - 没有任何语法糖使事情容易让你

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.

我觉得Eclipse可以帮助自动生成这些类型的东西虽然...

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

这篇关于在Java的getter / setter方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 03:32