Overview
In this blog we will find answer following questions
- What is Overriding
- What is Hiding
- What is Overloading
Overriding
From javaDoc
An instance method m1, declared in class C, overrides another instance method m2, declared in class A if:
- C is a subclass of A.
- The signature of m1 is a subsignature of the signature of m2.
- m2 is public, protected, or declared with default access in the same package as C, or
- m1 overrides a method m3 (m3 distinct from m1, m3 distinct from m2), such that m3 overrides m2.
Having two methods with the same arguments type and name, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class.
In above code move is overridden in SlowPoint class.
Hiding
From Javadoc
If a class declares a static method m, then the declaration m is said to hide any method m’, where the signature of m is a subsignature of the signature of m’, in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class.
Having two static methods with the same arguments and name, but different implementations. In that case then declaration method in Child Class is hidden by Super Class method.
Explanation:
Invocation of greeting uses the type of s, namely Super, to figure out, at compile time, which class method to invoke.
Invocation of name uses the class of s, namely Sub, to figure out, at run time, which instance method to invoke.
Overloading
From Javadoc
If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.
In above example in Class Point we are overloading methodSlowPoint with different argument.
In 2nd example while obj.foo is called foo method from Base and Derived class based on arg type.
0 Comments