Home | Java - Method Overriding

Chapter: Web or internet Programming : JAVA

Java - Method Overriding

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.

Method Overriding

 

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.

 

 

When show( ) is invoked on an object of type B, the version of show( ) defined within B is used. That is, the version of show( ) inside B overrides the version declared in A. If you wish to access the superclass version of an overridden method, 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.

 

class A{

 

int i,j;

 

A(int a, int b){ i=a;

 

j=b;

}

 

void show(){

System.out.println("i & j values are " + i + " "+ j);

 

}

}

 

class B extends A{ int k;

 

B(int a, int b,int c){ super(a,b); k=c;

 

}

void show(){

 

//the following super.show()Is used to call the base class method. super.show();

 

System.out.println("k value is            are " + k);

 

}

}

 

public class overrideclass2 {

 

public static void main(String args[]){ B suboj= new B(1,2,3); suboj.show();

 

}

}

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Web or internet Programming : JAVA : Java - Method Overriding |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.