开发者

Member method consting in Java?

In C++, a member method can be const if it does not modify the class. For example:

class Foo {
public:
  float getValue() const;
};

Is there something similar I 开发者_JS百科must do in Java classes? How exactly does consting work in Java? (Aside from adding the final keyword before a member variable declaration and initializing it)

Thanks


Is there something similar I must do in Java classes?

Nope.

How exactly does consting work in Java?

It doesn't exist in Java.


Although Java lacks a const qualifier, you can achieve some of the same ends with read-only interfaces and immutable types.

So, instead of qualifying a reference as const, you could specify its type to be a read-only interface type.

For example, given these two interfaces:

    public interface A {
       int getValue(); 
    }

    public interface MutableA extends A {
       void setValue( int i );
    }

Then this method's argument is similar to a const-qualified pointer/reference in C++.

    public void foo( A a )


There really is no notion of const in Java beyond the final keyword as you've mentioned.


Simply put, Java has nothing at all that's analogous to const methods. Since there are no const references, there is no need for them.

final is like const for primitive data or reference variables, but it doesn't imply anything about referred-to objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜