Define Method overloading. Explain its uses. Provide a code sample to explain the uses of Method overloading
1. Java supports to define two or more methods with same names within a class.
2. All the methods should differ in either by the number or type of parameters.
3. The method System.out.println() receives multiple parameters.Example
System.out.println(“Welcome to Java Technology”);// parameter as String type
System.out.println(number);// parameter as integer type
4. These methods are known as overloaded methods and the process is referred as method overloading.
5. One way of implementing polymorphism is method overloading.Uses of method overloading
1. Method overloading when a couple of methods are needed with conceptually similar functionality with different parameters.
2. Memory can be saved by implementing method overloading.The following application demonstrates method overloading
void triangleArea(float base, float height)
area = base * height / 2.0f;
System.out.println(“Area = “ + Area);
void triangleArea(float side1, float side2, float side3)
s = (side1 + side2 + side3) / 2.0;
area = Math.sqrt(s*(s-side1) * (s-side2) * (s-side3) );
System.out.println(“Area = “ + area);
public static void main(String args)
OverloadDemo ovrldDemo = new OverloadDemo();
Define Method overriding. Explain its uses. Provide a code sample to explain the uses of Method overloading
Method overriding is the process of writing functionality for methods with same signature and return type, both in super class and subclassThe uses of method overriding
1. Time to invest method signature is reduced.
2. Different functionality in both super class and sub class by sharing same signature.
3. The functionality can be enhanced.
4. The behavior can be replaced in the sub class.Code example for method overriding
A(int num1, int num2)
sum = a+b;
System.out.println("Sum : " + sum);
class Sub extends Sub
Sub(int num1, int num2, int num3)
subSum = num1+num2+num3;
System.out.println("Sum of 3 nos : " +subSum);
Difference between overloading and overridingOverloading
1. Two methods have same name with different type or number of parameters.
2. A relationship between methods is available in the same class.
3. Inheritance does not blocked by method overloading.
4. One method can overload unlimited number of times.
5. Only method name can be reused.Overriding
1. A method of super class is redefined in the sub class.
2. A relationship between methods is available in the super class and its sub class.
3. Method overriding blocks the inheritance.
4. Method overriding can be done only once per method in the sub class.
5. The complete method signature can be reused.