Method Overloading:
"Same method name, different parameters in same class."
We can achive in two ways:
1) The number of parameters is different for the methods
2) The parameter types are different.
Example:
We cannot achive in following ways:
1) Changing the return type of the method.
2) Changing the name of the method parameters, but
not changing the parameters types
Method Overriding:
"Same method name , same parameters in different class"
The overriding achieved by derived class(Subclass).
We implement the previous method in subclass. That means
we are using same method name,same parameter,same return type
but in different class.
"Same method name, different parameters in same class."
We can achive in two ways:
1) The number of parameters is different for the methods
2) The parameter types are different.
Example:
1) int changeDate(int Year, int Month) ;
int changeDate(int Year); 2)int changeDate(float Year) ; int changeDate(int Year);
We cannot achive in following ways:
1) Changing the return type of the method.
int changeDate(int Year) ;
float changeDate (int Year); 2) Changing the name of the method parameters, but
not changing the parameters types
int changeDate(int Month) ; float changeDate(int Year); Method Overriding:
"Same method name , same parameters in different class"
The overriding achieved by derived class(Subclass).
We implement the previous method in subclass. That means
we are using same method name,same parameter,same return type
but in different class.
// Method overriding.
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show()
{
System.out.println("k: " + k);
}
}
class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}

0 comments:
Post a Comment