Method Overriding in Java

By: Henry Emailed: 1598 times Printed: 2042 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

In a class hierarchy, 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. The version of the method defined by the superclass will be hidden. Consider the following: // 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
}
}

The output produced by this program is shown here:

k: 3

When show( ) is invoked on an object of type B, the version of show( ) defined within B is used. That is, the versio n of show( ) inside B overrides the version declared in A. If you wish to access the superclass version of an overridden function, you can do so by using super. For example, in this version of B, the superclass version of show( ) is invoked within the subclass' version. This allows all instance variables to be displayed.

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

If you substitute this version of A into the previous program, you will see the following output:

i and j: 1 2
k: 3

Here, super.show( ) calls the superclass version of show( ). Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded. For example, consider this modified version of the preceding example:

// Methods with differing type signatures are overloaded – not
// overridden.
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);
}
}

// Create a subclass by extending class A.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// overload show()
void show(String msg) {
System.out.println(msg + k);
}
}

class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show("This is k: "); // this calls show() in B
subOb.show(); // this calls show() in A
}
}

The output produced by this program is shown here:

This is k: 3
i and j: 1 2

The version of show( ) in B takes a string parameter. This makes its type signature different from the one in A, which takes no parameters. Therefore, no overriding (or name hiding) takes place.


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(80)


1. View Comment

Good example to know the concept better.

View Tutorial          By: ARAVIND L at 2009-01-05 04:07:46
2. View Comment

The Given Programms are not suitable for "How to solve Method Overriding " .Coz in 2nd model program,the overrided function Show( ) contains difference b/w super class show() and sub class show() ,the sub class show() contains a parameter String msg. but where as in method overriding method name,parameters & return type must be same...that's why please try to...give suitable example ..for method overriding....
Your's
Rams..


View Tutorial          By: Rams at 2009-01-27 01:36:16
3. View Comment

nice examlpe but u can make it more easy frnd

View Tutorial          By: meghendra at 2009-02-14 00:21:31
4. View Comment

Indent your code, man.

View Tutorial          By: Jenga at 2009-02-16 17:30:07
5. View Comment

The example shown and ur way of explaining is good....

View Tutorial          By: Devi at 2009-02-24 07:19:26
6. View Comment

nice examlpe but u can make it more easy so that the concept can be easily understand......

View Tutorial          By: lovely at 2009-02-25 07:08:18
7. View Comment

its a good example

View Tutorial          By: Sonal at 2009-03-25 08:35:10
8. View Comment

Dude, u xplaining lyk u already telling pros!Pls try a simpler explanation for al 2undastand.

View Tutorial          By: Brianjambo at 2009-04-14 06:32:13
9. View Comment

Nice for java examples, it is easy to understand java overriding.

View Tutorial          By: Nirmaladevi.T at 2009-06-19 04:42:51
10. View Comment

yaar this example is easy to understand but other examples of inheritence are difficult to understand

View Tutorial          By: richa at 2009-09-08 13:52:37
11. View Comment

this is the best example of method overriding but it is not a complete solution...........

View Tutorial          By: Dipesh at 2009-09-09 12:52:21
12. View Comment

I HAVE ONE DOUBT.

public class Animal {

public static void testClassMethod1() {
System.out.println("The class method in Animal.");
}
public void testInstanceMethod() {
System.out.println("The instance method in Animal.");
}
}


public class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The class method in Cat.");
}
public void testInstanceMethod() {
System.out.println("The instance method in Cat.");
}
}


public static void main(String[] args) {
// TODO code application logic here
Cat myCat = new Cat();
myCat.testClassMethod1();

}
my QUESTION is that can we call "myCat.testClassMethod1()" as OVERRIDING.if yes then why?


View Tutorial          By: georgy at 2009-10-22 02:46:10
13. View Comment

Very good post.^^

View Tutorial          By: LAM at 2009-10-25 04:18:38
14. View Comment

thats good. but not for the begineers. because in this example you have used super class also. and they are not familiar.

View Tutorial          By: jaywant topno at 2009-10-31 10:05:43
15. View Comment

Very Good Example Dude!

Note for readers, This is only a quick reference for reminding programmers how to user method overiding in java. It is assumed that you have read you books and done your hand-on excercises.


View Tutorial          By: Erwin at 2009-12-06 20:20:24
16. View Comment

This is not an easy example for begineer, please try to make it easy.

View Tutorial          By: Arif Islam Nayan at 2009-12-16 08:24:57
17. View Comment

Its an excellent example to learn this concept!!

View Tutorial          By: Koustav Routh at 2009-12-18 11:19:03
18. View Comment

Its Really Easy to understand............. superb

View Tutorial          By: Regina at 2010-01-06 23:38:11
19. View Comment

Not bad,but need some implementation

View Tutorial          By: surjeet katwal at 2010-01-19 04:41:15
20. View Comment

please give very easy program....this program is dough

View Tutorial          By: rajesh at 2010-01-24 08:08:38
21. View Comment

It is very good example to know the concept better

View Tutorial          By: abdulkadir at 2010-01-27 00:56:07
22. View Comment

thanks a lot dude,my lecturer took 2 weeks to explain this but only 15 min of reading this i get it totally.

View Tutorial          By: praveen malinga at 2010-02-25 07:53:01
23. View Comment

Its self-explaining and fullfilling example.

View Tutorial          By: vijay at 2010-03-29 02:36:41
24. View Comment

Easy and Wonderfulimple Example...to undersatnd the concept of Overriding for the Beginners !

View Tutorial          By: Chaitanya at 2010-04-04 02:27:04
25. View Comment

Hy gr8 man..!!! It was easy understanding

View Tutorial          By: ahwe at 2010-04-07 02:50:40
26. View Comment

This is totally great. Your explaination make me understand more easier

View Tutorial          By: Cipom at 2010-04-11 18:41:04
27. View Comment

not good example to learn the overriding methods
give at least two example of every concept


View Tutorial          By: george at 2010-04-25 12:08:20
28. View Comment

programs are making the concept easy.its a nice present..

View Tutorial          By: veeru at 2010-05-12 22:10:25
29. View Comment

really...........its very good explanation . sort but powerfull.

View Tutorial          By: gunjan shah at 2010-05-28 22:28:43
30. View Comment

explaination is very good ,(lucid and succinct approach)

View Tutorial          By: shailendra singh at 2010-06-08 11:24:29
31. View Comment

not that much clear exampl.. you should explain it more clearly.....

View Tutorial          By: elangovan at 2010-06-09 02:36:19
32. View Comment

very good example...........

View Tutorial          By: debojit dey at 2010-07-20 15:48:38
33. View Comment

good example..easy to understand

View Tutorial          By: aleena at 2010-07-24 21:56:01
34. View Comment

example is good but in more deatin & advantege and disadvantege is also impotans & whith example.
but good


View Tutorial          By: smita at 2010-08-08 06:09:09
35. View Comment

examples are very use full

View Tutorial          By: keerthe at 2010-08-12 23:00:21
36. View Comment

..i have a question. is it possible to override a method when it is already overloaded?? or its vice versa.

View Tutorial          By: rein at 2010-08-25 07:07:15
37. View Comment

Gooooooooooodd !!!

View Tutorial          By: Digvijoyee at 2010-08-30 22:11:31
38. View Comment

i need method overloading with io package

View Tutorial          By: ravinder kaur at 2010-09-11 11:00:57
39. View Comment

If i run this program----


// Methods with differing type signatures are overloaded â not
// overridden.
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);
}
}

// Create a subclass by extending class A.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// overload show()
void show(String msg) {
System.out.println(msg + k);
}
}

class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show("This is k: "); // this calls show() in B
subOb.show(); // this calls show() in A
}
}
THERE IS RUNTIME ERROR

Exception in thread "main" java.lang.NoSuchMethodError: main


View Tutorial          By: pratham at 2010-09-22 10:10:11
40. View Comment

very nice but i want some more exapmles

View Tutorial          By: prasad lengare at 2010-10-03 23:12:47
41. View Comment

ya its good example

View Tutorial          By: vijaychellappa at 2010-11-10 04:57:42
42. View Comment

It encourage the learners

Learners expect this kind of examples to understand the concept

ur site ll provide lot more in future........


View Tutorial          By: sureshkumar p at 2010-12-22 04:13:04
43. View Comment

This is awesum !!!
easy to understand .... clearl n crisp explanations ....
dere cud b nothin more easier ...


View Tutorial          By: Sud at 2011-01-19 08:37:55
44. View Comment

these above examples of overloading and overriding are very helpful to understand the concept of the same.

View Tutorial          By: janmejay pant at 2011-03-02 22:06:16
45. View Comment

the exampe was really useful........

View Tutorial          By: smitha at 2011-03-10 21:27:55
46. View Comment

@readers
this is an example of Hiding and Not Overriding. As overriding doesnt apply to static methods.


---------------------------
public class Animal {

public static void testClassMethod1() {
System.out.println("The class method in Animal.");
}
public void testInstanceMethod() {
System.out.println("The instance method in Animal.");
}
}


public class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The class method in Cat.");
}
public void testInstanceMethod() {
System.out.println("The instance method in Cat.");
}
}


public static void main(String[] args) {
// TODO code application logic here
Cat myCat = new Cat();
myCat.testClassMethod1();

}
my QUESTION is that can we call "myCat.testClassMethod1()" as OVERRIDING.if yes then why?

By: georgy at 2009-10-22 02:46:10


View Tutorial          By: DevJ at 2011-03-18 05:41:52
47. View Comment

Hi
Its nice example ..
something should be able to understood like this, then only beginners will be passionated...

Regards
munirasu


View Tutorial          By: munirasu at 2011-04-01 06:38:46
48. View Comment

nice example . and good job.

View Tutorial          By: mohit sinha at 2011-04-07 03:19:01
49. View Comment

/*Overridding & equals:--> Overriding is another useful feature of object-oriented programming technique. It provide the facility to redefine the inherit method of the super class by a subclass. The method overriding is used to invoking the parent class method by a child class. It is possible when a child class extends the parent class then all the attributes and the methods of parent class inherit by child class.*/

class Test10
{
int num,num1;
public Test10(int num,int num1)
{
this.num=num;
this.num1=num1;
}
public boolean equals(object 0)
{
Test10 t=(Test10)0;
if((t.num==this.num)&&(t.num1==this.num1))
{
return true;
}
return false;
}
public static void main(String[]args)
{
Test10 t1=new Test10(10,21);
Test10 t2=new Test10(10,30);
System.out.println(t1.equals(t2));
}
}


View Tutorial          By: Naveen Kumar at 2011-04-30 18:44:55
50. View Comment

Good example thank you so much

View Tutorial          By: Albadri at 2011-05-14 15:48:17
51. View Comment

super example...it very useful for me...

View Tutorial          By: elan at 2011-06-02 07:54:39
52. View Comment

this is not good example we want better...

View Tutorial          By: sabari nathan.p at 2011-06-15 03:27:18
53. View Comment

using a same name ,return type and parameter type for a method in a derived class as that of a method i.e, present in the base class is known as method overridind
EX:-
class x
{
void show()
{
system.out.pln("hey");
}
}
class y extends x
{
void show()//notice void show ()is present in both the base class and the derived class//
{
system.out.pln("hello");
}
}
class test3
{
public static void main(string n[])
{
y y1=new y();//y1....derived class object//
y1.show();
}
}

though it`s possible to invoke the base class method within the derived class object.
When the statement y1.show();is exicuted,the show() of Derived class(i.e,y) is invoked reasulting in the out put 'hello'.
the base class method show() is said to be hidden from the derived class method show(). In order to exicute show()of the base class therre are twomethods
1. By creating an object for th base class.
2. By using super keyword


View Tutorial          By: sam at 2011-06-24 15:13:34
54. View Comment

need to be explained more

View Tutorial          By: parul at 2011-06-30 08:34:29
55. View Comment

sooo nice...:****...love u...

View Tutorial          By: vinoo gopal rao at 2011-07-03 08:54:29
56. View Comment

gr8t man.....! i am satisfied with ur explanation

View Tutorial          By: raja deepa at 2011-07-05 13:44:21
57. View Comment

it is a good example to understand.

View Tutorial          By: nivedha at 2011-07-12 05:15:39
58. View Comment

nice example..

View Tutorial          By: righana at 2011-07-19 08:46:50
59. View Comment

Its Very Good Example

View Tutorial          By: Madhu at 2011-08-26 12:11:49
60. View Comment

very bad example.......can v call overrided function of parent class method with child class object with out using super key word ?

like in c++ v hv feature to cal it by using :: operator


View Tutorial          By: abdul nasir khayam at 2011-10-27 20:57:00
61. View Comment

2nd example not gud

View Tutorial          By: prakash at 2011-11-15 11:07:43
62. View Comment

thanks....good explanation...

View Tutorial          By: jiby at 2012-01-14 05:57:33
63. View Comment

Thanx................!!!!!!!!!!!

View Tutorial          By: ankita at 2012-01-21 19:16:54
64. View Comment

which method is called if i call overriden method with superclass object?

View Tutorial          By: sarah at 2012-02-01 13:36:10
65. View Comment

class Abc
{
public void display()
{
System.out.println("hai");
}
class Bca extends Abc
{
public void display()
{
System.out.println("hello");
}
}
public static void main(String[] args)
{
Bca obj =new Bca();
obj.display();
}
}
//it shows error can explain


View Tutorial          By: Umapathi REddy at 2012-05-23 09:54:29
66. View Comment

you have extended class Abc within class Abc
the correct code is
class Abc
{
public void display()
{
System.out.println("hai");
}
}
class Bca extends Abc
{
public void display()
{
System.out.println("hello");
}
public static void main(String[] args)
{
Bca obj=new Bca();
obj.display();
}
}


View Tutorial          By: SUNIL SHAH at 2012-05-25 06:17:23
67. View Comment

everything is easy to learn from your website.I understand everything easily.I want learn about thread in java

View Tutorial          By: sumitra barua at 2012-05-30 03:13:10
68. View Comment

Programs are so good..!
i wish to say one thing
when we invoke the show(); method
in main method as y1.show(), it wil b
executes properly and to invoke
base class method show() one can
use super keyword or base class object.

But in c++ calling y1.show(); wil give ambiguty error. there we hav to cal as Y:: y1.show();

am i right?
please reply.


View Tutorial          By: Shashikumar Misal at 2012-09-01 20:35:47
69. View Comment

Thank you very much for such a nice topic

View Tutorial          By: CHANDAN at 2012-11-01 04:40:02
70. View Comment

finally an understandable example

View Tutorial          By: sdf at 2012-11-26 21:44:34
71. View Comment

its simple and easy... good example.

View Tutorial          By: madhu kk at 2012-12-05 07:56:04
72. View Comment

Hats off man !!! Very Simple & Straightforward.

View Tutorial          By: Nitesh at 2013-01-06 00:50:53
73. View Comment

simply super...every one can understand

View Tutorial          By: prashanth at 2013-03-10 12:20:25
74. View Comment

I want to use concept of overriding and i want to print both function from base and derived class
plz send me demo program based on it on my mail id


View Tutorial          By: Aniket at 2013-06-20 10:23:10
75. View Comment

very good exmpl and explantion

View Tutorial          By: harshita negi at 2013-10-16 02:19:35
76. View Comment

what are benefits of using overriding method?

View Tutorial          By: Ah Socheat at 2013-12-11 04:44:57
77. View Comment

U did'nt explain super(a,B)

View Tutorial          By: Rafiqullah at 2013-12-16 10:30:41
78. View Comment

frnds i need overriding concept in bubble sort
plzzzzzzzzzzzzzz........send to my email id


View Tutorial          By: rabbu at 2014-08-21 12:46:52
79. View Comment

Dude,
Atleast indent and try to make sense.
Tutorials doesn't mean you teach the pros who already know stuff !


View Tutorial          By: Phani at 2015-03-19 16:51:57
80. View Comment

very simple example.....................

View Tutorial          By: kajal at 2015-08-22 09:28:16

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Henry
Generating Your Key Pair example using keytool in Java
Summary of Operators in Java
JDBC Basics and JDBC Components
The IterationTag Interface in JSP
Trigonometric, Hyperbolic, Exponential and Logarithmic Functions in C
Using Bit-field in C
Java Beans and the Expression Language
Initialization of Variables in C
Creating Struts Modules
else if statement in C
Line Counting sample program in C
Accessing Context Data in Beans using JSF
Using peek() and putback() with cin in C++
Internationalization Support in J2ME MIDP
java.lang.SecurityException: MIDP lifecycle does not support system exit.

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
Using StringTokenizer in Java
InetAddress Example program in Java
Method Overriding in Java
How to use Iterator in Java
FileReader and FileWriter example program in Java
XML and Java - Parsing XML using Java Tutorial
wait(), notify() and notifyAll() in Java - A tutorial
Abstract classes in Java
How to use ArrayList in Java
Vector example in Java
Method Overloading (function overloading) in Java
Recursion in java
Read from a COM port using Java program
Garbage Collection in Java
Most Emailed Articles (in Java)
HTTPS Java - URL Connection program. Using HttpsURLConnection
Configuring a DataSource in Tomcat
Unicode vs ISO 10646?
What is Reflection? - getConstructors(), getFields(), and getMethods()
BufferedReader sample program in Java
append() in Java
The Basic Structure of a Simple Java program
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java