Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java something like "C++: const return type" - or how to allow read and prevent write to non-primitiv members

Tags:

java

constants

Maybe I still miss an important concept.

To allow reading and prevent writing of non-primitive members, the according getter always creates a new copy of the member object. I want to prevent this for performance reasons. I am trying to write a simple 2D simulator with collision detection based on a quadtree and this would be bread and butter.

I think in C++ I can do it with the return of a const. (I know I can overwrite this with a cast) but I am not sure how this is done in JAVA.

any ideas?

like image 768
Klaus Koeder Avatar asked Dec 19 '25 03:12

Klaus Koeder


1 Answers

There are several ways to archive what you want to do.

First of there is no language support for what const does in C++.

In any case I suggest you use Getters and Setters as there is no overhead caused by them what so ever. The Java just-in-time optimization takes care of this.

For non-primitive types you still have the problem that the object you returned itself could get changed. There are three ways to prevent this.

  1. You don't return the object at all. You provide the data stored inside the object by multiple getters in the parent object.
  2. You use immutable objects or immutable views. So a object that can't be changed in general or a object that provides just a view on the object but blocks the setter objects.
  3. You return a copy of the original object using clone or a copy-constructor.
like image 183
Nitram Avatar answered Dec 20 '25 17:12

Nitram