Overriding in java
when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass.
sample program on overriding:
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
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;
}
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 class
}
}
What if I want to call show method in super class.....
sample program on overriding:
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
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;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
sample program on overriding:
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
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;
}
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 class
}
}
What if I want to call show method in super class.....
sample program on overriding:
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
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;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
A good example showing the difference between Overloading and overriding.
Java Tutorials: Overloading is compile-time binding
This also shows a potential problem that beginners tend to make.
Posted by Jayaprabhakar | 12:27 PM
well ur definition is understandable but where is the main method in the second sample prog of overrigding in java?
Posted by srinath | 4:10 AM
well ur definition is understandable but where is the main method in the second sample prog of overrigding in java?
Posted by Anonymous | 10:35 AM
i think the second example is wrong or somthing is missing.Give some more overiding program to clear the concept of overriding
Posted by Unknown | 3:52 AM
yes your explanation sufficient to understand the difference overloading & overriding.In second sample program we have to own assume the main program as same as that of main method in first sample program
Posted by Vikas | 9:47 AM