Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

const functions? 1

Status
Not open for further replies.

cpjust

Programmer
Sep 23, 2003
2,132
US
Hi, I'm kind of new to Java. I've been programming in C++ whenever possible. I'm starting to write some code in Java now and can't figure out how to create const functions.

In C++ you can declare a function with the const keyword after the function name, ex:
Code:
class SomeClass
{
public:
    void SomeFunc() const;
};
The const guarantees that the function will not modify the object's state (i.e. the member variables).

The closest equivalent I could find to const is the final keyword, but the description I read about final seems to indicate that it will only prevent derived classes from overriding that function...

Is there any equivalent in Java to making a function const?
 
>>>>> The const guarantees that the function will not modify the object's state (i.e. the member variables).

There is no const keyword, however ...

Making a member variable final means that it cannot be changed elsewhere - so its kind of similar for class data.

If you make a method static, it will not have access to a class instance's member variables, unless those variables are also static.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
It cannot be changed elsewhere, but can that function modify any member variable in that class?

BTW, how do I make a function final? I get an error if I put 'final' after the function name, and if I put it before the name it thinks I'm talking about the return type...
 
Code:
public final int getValue(){
  // method body
  return 0;
}

public final void anotherMethod(){
  .. method body
}

BTW, the're not called functions in Java, the're called methods. A method can modify any member variable, unless that variable itself has been declared as final, in which case once it has been assigned the value is immutable.

Tim
 
Humm, I don't think I get the point: if you don't want your method to change class variables, don't write code that can do that, you can just move the method to another class, like an utility class.

Cheers,
Dian
 
After reading the original post, the answer is "No, there is no direct equivalent of a C++ function const". You'll just have to ensure that the code you put in a method doesn't modify object state.

However, if it doesn't return a value based on the object state, nor modify the object state, then Dian has a point. What would that method be there for? Some side-effect not related to the object?

Tim
 
In C++ I always declare my Get methods as const since they are only returning the current state but not modifying it.

Manually ensuring that you don't modify the state isn't always as easy as it sounds, especially if you're in a group of developers working on the same code. For example, your Get method could call other methods in your class to gather the information it needs. Unless you ensure that all the methods that it calls also do not modify the state (and never get updated by someone who doesn't know they shouldn't modify the state), then you break that guarantee.

Specifying a method to be const in C++ causes the compiler to do that checking for you and it won't allow you to call other methods unless they are also declared as const methods.

Limitations like these are exactly why I've been avoiding Java... :-(
 
I definitely don't think you can do that in Java.

I guess it has to do with what you're used to, but that's such a feature I've never missed.

Cheers,
Dian
 
In my opinion, that wouldn't be a point to choose a language. The key for me is what can I do with a language, not what the language can do for me.

If you want a portable cross-platform application, I wouldn't let const functions lack scare me. Just be a little more careful when implementing accessor methods.

Think that thousands of Java developers code their get methods this way and the sun still shines :)

Cheers,
Dian
 
It wouldn't fit to java as late-bound language at all.
I made an example:
Code:
 public class ConstFunTest
{
	private int value  = 17;

	public void setValue (int v)
	{
		value = v;
	}
	
	/** How to prevent that this method might change our inner state? */
	public void dontChangeCFT (Hacker hacker)
	{
		hacker.callback ();
	}
	
	public static void main (String args[])
	{
		Hacker hacker = new Hacker ();
		hacker.hack ();
	}
}

class Hacker
{
	private ConstFunTest cft;
	
	public void callback ()
	{
		cft.setValue (42);
	}

	public void hack ()
	{
		cft = new ConstFunTest ();
		cft.dontChangeCFT (this);
	}
}

Assuming we would be allowed to write:

const public void dontChangeCFT (Hacker hacker)

How should that be possible?
In this example you can easily detect, that hacker.callback is acting on the object itself, but if the class is a bit more complex, it will be hard or impossible to guarantee, that the method will not change your object, if you call another method inside your method, and if your object has at least one method, which is able to change your object, like every setter-method.

I'm wondering how that is reached in c++ - perhaps because the linker may guarantee it?

seeking a job as java-programmer in Berlin:
 
correction:

, if you call a method of another object (which might have a reference to your object) inside your method, and if your object has at least one method, which is able to change your object, like every setter-method.

seeking a job as java-programmer in Berlin:
 
Diancecht said:
I wouldn't let const functions lack scare me.
Well it's not only that, but Java also lacks templates, operator overloading, multiple inheritance (yes, I know it's evil, but sometimes it's useful) and real enums (although I heard the latest version finally supports real enums).

The one thing that I really like about Java is the huge number of classes that come with it (although when you start out, that large number can be a bad thing since you have a hard time finding the right one).
 
Its really a matter of opinion ... IMO, templates, operator overloading and multiple inheritence are actually quite nasty features of C++, and when I code C++, I avoid them.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
For most really useful things, either language has a solution.

C++ templates are certainly not a nasty feature. They are amazingly effective tools for certain jobs. But guess what? Java has generics, which aren't exactly the same, but are close enough for most situations.

Operator overloading can be good or bad depending on your opinion, but it really doesn't matter. You're calling a function (or method) either way. It's just syntax.

Similarly, multiple inheritance isn't really necessary that often, and when it is a good choice, interfaces in Java usually solve the problem just as well.

Finally, the use of const in C++ might be a nice way to enforce certain contracts within the code, but it really isn't necessary in C++ or Java.

Bottom line is that a lot of these differences seem trivial to me if you want to decide which to use between two languages.
 
I would have used C++, but unfortunately the API I'm using is only in Java. But on the plus side, multiple threads are a lot easier in Java.
 
cpjust said:
multiple threads are a lot easier in Java.
That is an understatement if I ever heard one !!!


uolj : Like I said before - its all a matter of opinion- I don't really agree with you on any of your points - but then thats the point - its an opinion.

At the end of the day, if you don't like Java, then don't use it :)

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
I wasn't really disagreeing with you, sedj (except about the templates), most of my comments were directed at cpjust. I am surprised that you really think that:
[ol]
[li]For most really useful things, only one (or neither) of the languages has a solution.[/li]
[li]C++ templates are never an effective tool and Java generics are either very different or not effective either (or both).[/li]
[li]Operator overloading is bad and it really matters as more than just a syntax difference when choosing a language, despite the fact that for your own code you can choose not to overload operators if you don't want to.[/li]
[li]Multiple inheritance in C++ is a bad feature, but for any situations where it is a good solution, Java just doesn't have a valid alternative (or there is an alternative that I didn't mention).[/li]
[li]The use of const is necessary in C++.[/li]
[li]These differences are important when choosing a language to solve a specific task.[/li]
[/ol]
I'll be honest that I don't really trust your opinion about C++ simply based on your templates comment, but I certainly wasn't trying to say that one language was better than the other, nor was I trying to say that one language is not better than the other. Just that minor language features and syntax differences are poor reasons to pick one.

And of course, saying not to use a language if you don't like it is far too simplistic of a statement. It sounds like you're in Java "defense" mode. Perhaps that is warranted from the "Limitations like these are exactly why I've been avoiding Java..." comment, but the discussion can be a little more complex than that. :)
 
uolj, I'm not saying I dislike C++ as a rule - I use it every day, and lately code more in C++ than I do in Java - just saying I don't like or use some of the features.

I fully agree with your comment that :

Just that minor language features and syntax differences are poor reasons to pick one.



--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
I think we are pretty much agreed, then, that some things are nice in C++ and some things are nice in Java. Just as some things are nasty in C++ and some are nasty in Java. We'll never come to a concensus on what these things are and that's fine.

If you have to use Java because some software you must use only comes with a Java API, and you're able to code in Java, fine. Use it.

We're here to help smooth the bumps if you have them.

Just don't try to find a 1-to-1 equivalent between the language features because it doesn't exist.

And try not to post comments like
Limitations like these are exactly why I've been avoiding Java
in the Java forum. We're a sensitive bunch and it makes us sad.:)

That said, at the end of the day I hope you complete your Java coding successfully, and who knows, you may even enjoy it a little.


Tim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top