NixDev
NixDev

Reputation: 473

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 ?

Upvotes: 10

Views: 7822

Answers (4)

user1944408
user1944408

Reputation: 569

Make it static.

If you call a non-virtual method then you want to know from your code which class method you are calling. The flaw of .net is that you cannot know that from your code.

Example

In Java if you define ClassB as

public class ClassB extends ClassA {
    @Override 
    public void run() {
    }
}

and object

ClassA obj=new ClassB();

If you call obj.run() how will you know if that code is following the rules of polymorphic open/close principle or it will code method related to ClassA? In Java you will know that there is always polymorphism. It is easier to make mocks and it is easier to extend classes and follow Liskov substitution principle.

On the other hand static methods are bounded to a class so if you want to call a method that is related to ClassA you can define that method like this:

public static run(ClassA obj)

and you can call it with

ClassB obj=new ClassB();
ClassA.run(obj);

and from the code you will know that the method you are calling is defined in ClassA and not in ClassB.

Upvotes: 1

Ricky Clarkson
Ricky Clarkson

Reputation: 2939

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.

Upvotes: 9

Cephalopod
Cephalopod

Reputation: 15145

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.

Upvotes: 2

Maurice Perry
Maurice Perry

Reputation: 32831

Yes, or private

Upvotes: 9

Related Questions