Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The use of override and virtual in C# vs. Java method overriding

Why do we need to explicitly define a method as virtual and then also specify override in C# to accomplish method overriding whereas the same thing is achieved without using both of these in keywords in Java. What purpose does it serve?

like image 791
user544079 Avatar asked Jan 21 '23 05:01

user544079


2 Answers

in java, there's no need to add any keyword to override a method. But some rules apply:

  • Methods overriding cannot be declared more private than the super class method.
  • Any exceptions declared in overriding method must be of the same type as those thrown by the super class, or a subclass of that type.
  • Methods declared as final cannot be overridden.
  • An overriding method can be declared as final as the keyword final only suggests that this method cannot be further overridden.
  • Methods declared as private cannot be overridden as they are not visible outside the class.

font

like image 52
bluefoot Avatar answered Feb 04 '23 15:02

bluefoot


This way you have tighter control over what's overrideable or not. It's the same as in access permissions - do you give a user all rights by default and remove permissions, or do you give none and then add what's required.

like image 34
Andrey Avatar answered Feb 04 '23 15:02

Andrey