Reputation: 54113
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 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
Upvotes: 0
Views: 189
Reputation: 86411
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 )
Upvotes: 3
Reputation: 81684
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.
Upvotes: 2
Reputation: 35598
There really is no notion of const
in Java beyond the final
keyword as you've mentioned.
Upvotes: 3
Reputation: 359816
Is there something similar I must do in Java classes?
Nope.
How exactly does consting work in Java?
It doesn't exist in Java.
Upvotes: 4