« Home | What is overloading in java » | Program to reverse a string » | XML Parser in Java » | Algorithms Used in Garbage collection » | Lower Case to Uppre Case Conversion » | PRINTING THE NON-PRIMES » | PRIME FACTORS OF ALL NON-PRIMES BELOW 500 » | What is Garbage Collection & Why is Garbage Collec... » | Public static void main (String args[]) » | Delete and Update values in MySql Using Java » 

Thursday, April 06, 2006 

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);
}

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.

well ur definition is understandable but where is the main method in the second sample prog of overrigding in java?

well ur definition is understandable but where is the main method in the second sample prog of overrigding in java?

i think the second example is wrong or somthing is missing.Give some more overiding program to clear the concept of overriding

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

Post a Comment

About me

  • I'm phanindra
  • From Hyderabad, Andhra Pradesh, India
  • An Alumini of JNTU Hyd into happening IT industry...
My profile

Visitors
Bloggeries Blog Directory BlogRankings.com singapore blog directory blog search directory
Google
 
Web conceptoftheday.blospot.com