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.
ExampleSystem.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 overloading1. 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 overloadingclass OverloadDemo
{
void triangleArea(float base, float height)
{
float area;
area = base * height / 2.0f;
System.out.println(“Area = “ + Area);
}
void triangleArea(float side1, float side2, float side3)
{
float area,s;
s = (side1 + side2 + side3) / 2.0;
area = Math.sqrt(s*(s-side1) * (s-side2) * (s-side3) );
System.out.println(“Area = “ + area);
}
}
class MainOverloadDemo
{
public static void main(String args[])
{
OverloadDemo ovrldDemo = new OverloadDemo();
ovrldDemo.triangleArea(20.12,58.36);
ovrldDemo triangleArea(63.12,54.26,95.24);
}
}
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 subclass
The uses of method overriding1. 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 overridingclass Super
{
int sum;
A(int num1, int num2)
{
sum = a+b;
}
void add()
{
System.out.println("Sum : " + sum);
}
}
class Sub extends Sub
{
int subSum;
Sub(int num1, int num2, int num3)
{
super(num1, num2);
subSum = num1+num2+num3;
}
void add()
{
super.add();
System.out.println("Sum of 3 nos : " +subSum);
}
}
Difference between overloading and overriding
Overloading1. 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.
Overriding1. 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.