Java Reference
In-Depth Information
Let's consider the following definitions of two classes S and T :
public class S {
public void print() {
System.out.println("S");
}
}
public class T extends S {
public void print(String msg) {
System.out.println(msg);
}
}
Does the print() method in class T override the print() method in its superclass S ? The answer is no. The
print() method in class T does not override the print() method in class S . This is called method overloading. Class T
will now have two print() methods: one inherited from its superclass S , which takes no arguments and one declared
in it, which takes a String argument. However, both methods of class T have the same name print . This is the reason
that it is called method overloading because the same method name is used more than once in the same class.
Here are the rules when a class is said to override a method, which it inherits from its superclass.
Method Overriding Rule #1
The method must be an instance method. Overriding does not apply to static methods.
Method Overriding Rule #2
The overriding method must have the same name as the overridden method.
Method Overriding Rule #3
The overriding method must have the same number of parameters of the same type in the same order as the
overridden method. Java 5 has changed this rule slightly when the methods use generic types as their parameters.
When the method's parameters use generic type, you need to consider the erasure of the generic type parameter, not
the generic type itself when comparing with other methods to check if one overrides another. I will revisit this rule in
later to discuss it in detail with examples. For now, let's consider a method as overriding another method if they have
the same number of parameters of the same type in the same order. Note that the name of the parameter does not
matter. For example, void print(String str) and void print(String msg) are considered the same method. The
different names of the parameters, str and msg , do not make them different methods.
Method Overriding Rule #4
Before Java 5, the return type of the overriding and the overridden methods must be the same. In Java 5, this rule remains
the same for return types of primitive data types. However, it has changed for return types of reference data types. If the
return type of the overridden method is a reference type, the return type of the overriding method must be assignment
compatible to the return type of the overridden method. Suppose a class has a method definition of R1 m1() , which is
overridden by a method definition R2 m1() ;. This method overriding is allowed only if an instance of R2 can be assigned to
a variable of R1 type without any typecast. Let's consider the following snippet of code that defines three classes P , Q , and R :
public class P {
public Employee getEmp() {
// Code goes here
}
}
 
Search WWH ::




Custom Search