Home Java Javascript-array Java method Overriding
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Java method Overriding

Advertisement
Below example illustrates method Overriding in java. Method overriding in java means a subclass method overriding a super class method. Superclass method should be non-static.

Java method Overriding

     

Below example illustrates method Overriding in java. Method overriding in java means a subclass method overriding a super class method. Superclass method should be non-static. Subclass uses extends keyword to extend the super class. In the example class B is is the sub class and class A is the super class. In overriding methods of both subclass and superclass possess same signatures. Overriding is used in modifying  the methods of the super class. In overriding  return types and constructor parameters of methods should match .

 

 

 

 

Here is the code:

class A {
int i;
A(int a, int b) {
i = a+b;
}
void add() {
System.out.println("Sum of a and b is: " + i);
}
}
class B extends A {
int j;
B(int a, int b, int c) {
super(a, b);
j = a+b+c;
}
void add() {
super.add();
System.out.println("Sum of a, b and c is: " + j);
}
}
class MethodOverriding {
public static void main(String args[]) {
B b = new B(10, 20, 30);
b.add();
}
}

Output will be displayed as:

Download Source Code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 19, 2008

Related Tutorials

Ask Questions?    Discuss: Java method Overriding   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Raj kumar
March 30, 2011
improving java programming skill

Hello:-I m interested in java programming & i want improve my programing skill plz reply to me & how to improve programming development skill? Thanks
J. BENNY BOSCO MCA
June 30, 2011
Method Overriding

Good example for method overriding in Java
sriram
July 29, 2012
java

good code to understand
akash
December 4, 2012
Class B to be declared static

In above code class B has to be declared static because non-static variable cannot be referenced from a static context.
DMCA.com