Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non virtual methods in Java

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 ?

like image 433
NixDev Avatar asked Sep 01 '10 18:09

NixDev


People also ask

What is non-virtual method in Java?

Omitting the virtual keyword declares a method as non-virtual. Simply speaking, declaring a method as virtual enables overriding, declaring a method as non-virtual disables overriding. theAccount->display();

What are non-virtual methods?

Methods that don't have either the virtual or override keywords, or that have the new keyword, are said to be non-virtual. When a virtual method is invoked on an object, the run-time type of the object is used to determine which implementation of the method to use.

Are all methods in Java Virtual?

Every non-static method in Java is a virtual function except for final and private methods. The methods that cannot be used for the polymorphism is not considered as a virtual function.

Which methods are virtual in Java?

In Java Every non-static, non-final, and public method is a virtual function. These methods can be used to achieve polymorphism. The methods that can not be used to achieve the polymorphism never be virtual function. A static, final, and private method never be the virtual function.


2 Answers

Yes, or private

like image 53
Maurice Perry Avatar answered Oct 22 '22 03:10

Maurice Perry


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.

like image 33
Ricky Clarkson Avatar answered Oct 22 '22 03:10

Ricky Clarkson