views:

135

answers:

3

Just starting to use Java. I find a lot of similarities with .NET, but I see that all methods in Java are virtual by default. So the question is what can I do to make them non virtual ? Is the final keyword the one and right solution ?

+7  A: 

Yes, or private

Maurice Perry
But `private` - just as in .net - makes the method unavailable for other classes to call, as well as preventing overriding.
Carl Manaster
But what can I do when I need to have a method in child class with the same name as it is in parent class. In C# there is a keyword new for such cases... is there something similar in Java.
NixDev
nope, nothing at all
Maurice Perry
+1  A: 

Instead of defining all methods as final, you can also define the entire class as final. I'm not saying whether this good or bad style.

Arian
+3  A: 

If you´re aiming to make the method non-virtual for performance, let the JIT deal with that until you have evidence that it isn't doing.

If the reason to make the method non-virtual is to be able to define it in a subclass but not involve polymorphism, you're probably subclassing for no real reason (post more code if you'd like to contest this).

If it's for design, I'd suggest making the class final instead of individual methods if possible. IDEA has good inspections for class design. Try not to listen too closely to those who want you to leave everything open so that they can subclass to hack around bugs or limitations; they'll shout at you even more loudly when you accidentally break their subclass.

Provide a way for clients to add their own types rather than subclass yours and they'll probably not even notice that your classes are final.

Ricky Clarkson