Overriding and overloading methods in Java

Can a static method be overridden or overloaded

Overloaded - yes. Everything works in the same way as with ordinary methods - 2 static methods can have the same name if the number of their parameters or types is different.

Redefined - no. The choice of the called static method occurs during early binding (at the compilation stage, not at runtime) and the parent method will always be executed, although syntactically overriding a static method is a completely correct language construct.

In general, it is recommended that static fields and methods be accessed through the class name rather than an object.

Can non-static methods overload static ones

Yes. This will end up with two different methods. The static one will belong to the class and will be accessible through its name, and the non-static one will belong to a specific object and is accessible through a method call of this object.

Is it possible to narrow down the access level/return type when overriding a method

Is it possible, when overriding a method, to change: access modifier, return type, argument type or their number, argument names or their order; remove, add, change the order of the elements of the throws clause

When overriding a method, narrowing the access modifier is not allowed, because this would violate Barbara Liskov's substitution principle. Expansion of the access level is possible.

You can change everything that does not prevent the compiler from understanding which method of the parent class is meant:

  • Changing the type of the return value when overriding the method is allowed only in the direction of narrowing the type (instead of the parent class - inheritor).
  • When changing the type, number, order of the arguments, instead of overriding, the method will be overloaded.
  • The throws section of a method can be omitted, but it is worth remembering that it remains valid if it is already defined in the parent class method. It is also possible to add new exceptions that inherit from the already declared or RuntimeException exceptions. The order in which these elements are redefined does not matter.

How do I access the overridden methods of the parent class

Using the super keyword, we can refer to any member of the parent class - method or field, if they are not defined with the private modifier.

super.method();


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed