Does function/method overriding occur only when polymorphism is implemented in java?

3 days ago 5
ARTICLE AD BOX

Method overriding and polymorphism are distinct but related things.

Polymorphism occurs in Java when you use an instance of some class C as an instance of a supertype, S, of C. For instance, you pass it as a method argument where an S is required, or assign it to a variable of type S. Particularly so if methods are then invoked on the object as if it were an S. Polymorphism is an aspect of object interactions.

As the term is defined by the JLS, overriding occurs when a class C declares an instance method with the same name and signature, up to type erasure, as an instance method declared by one of its supertypes and visible to C. Method overriding is an aspect of class definitions.

You can have polymorphic behavior involving types that perform no method overriding. You can have method overriding without any instances of the types involved being used polymorphically. However, some method overrides are targeted in part toward polymorphic usage scenarios.

Is overriding considered a subset/type of polymorphism (Runtime Polymorphism)?

No. Overriding is about class definition, whereas polymorphism is about object usage. One of the aspects of Java's style of polymorphism is that instance method invocations are dispatched based on the class of the object on which they are invoked, rather than based on the type of the expression designating that object. This is referred to as "runtime polymorphism", "dynamic binding", or "late binding". This particular aspect of Java polymorphism is meaningful only because Java supports method overriding, but in a language design sense, polymorphism is about more than late binding, and late binding is not even an essential aspect.

Can you have overriding in a program without "using" polymorphism in a practical sense?

Absolutely. Suppose class Sub extends class Super and overrides method int doSomething(int) of Super. If everywhere an instance of Sub is used, it is accessed via an expression of type Sub, then there is no polymorphism involved. Not even when Sub.doSomething() is invoked.

Read Entire Article