Quantcast
Channel: User user1944408 - Stack Overflow
Viewing all articles
Browse latest Browse all 26

Answer by user1944408 for Non virtual methods in Java

$
0
0

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.


Viewing all articles
Browse latest Browse all 26

Trending Articles





<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>