javatutelearn.com

Easy Learning


Home

Search Javatutelearn.com :



Java Method Overriding

  • Method overriding concept is applicable in heritance.
  • Method overriding permits to have same name method in both super class and sub class.
  • Remember:
  • Number of arguments and type of arguments are same in Method Overriding.
  • Number of arguments and type of arguments are different in Method Overloading.
Example:
Suppose, there are two classes (class A and class B). Class A is super class and class B is sub class.
class A {
	int n;
	
	void setdata(int k) {
		n = k;
	}
	void showdata (){
		System.out.println("Value of n = "+ n);	
	}
}
class B extends A
{
	int m;
	
	void setdata(int p, int q) {
		n= p;
		m = q;
	}
	// Following showdata() method is overriding showdata() method of super class A
	void showdata(){
		System.out.println("Value of n is "+n);
		System.out.println("Value of m is "+m);
	}
}
class demoOverriding {
	public static void main(String args[]) {
		B obj1 = new B();
		
		obj1.setdata(10,20);
		obj1.showdata(); // showdata() method of child class B is called
	}
}

Output

Value of n is 10
Value of m is 20
In this program, showdata() method of child class B overrides showdata() method of parent class A.



© Copyright 2016-2024 by javatutelearn.com. All Rights Reserved.