Object Oriented Programming : overriding

If we have one method in parent class ( upper class ) then we create one more method with same name in child class to override the method in parent class.

The advantage is we can change the method in child class based on specific requirement.

In the example below the method games() is overridden inside the child class games_types.
package Pack1;
class my_first {

	   public void games()
	   {
	      System.out.println("Cricket ( parent )");
	   }
   public static void main( String args[]) {
	      my_first obj1 = new my_first();
		      obj1.games(); // call parent method games 
		  my_first obj2 = new game_types();
		      obj2.games(); // call child  method games  
		    
   }
}
class game_types extends my_first{
	   //Overriding games method
	   public void games(){
	      System.out.println("Football ( child ) ");
	   }
 }
Output is here
Cricket ( parent )
Football ( child )

final method can't be overridden.

If we cange the parent method to final then we can't override the same.
final void games()
	   {
	      System.out.println("Cricket ( parent )");
	   }
Now the line saying public void games(){ in child class will generate error.

Similarly we can't override static methods. So the main method we can't override as it is a static method.

Example 2

package Pack1;
class my_first {

	   public void games()
	   {
	      System.out.println("Cricket ( parent )");
	   }
   public static void main( String args[]) {
	      my_first obj1 = new my_first();
		      obj1.games(); // call parent method games 
		  my_first obj2 = new game_types();
		      obj2.games(); // call child  method games  
		  game_types obj3 = new game_types();
		     obj3.indoor_games(); // called new method       
   }
}
class game_types extends my_first{
	   //Overriding games method
	   public void games(){
	      System.out.println("Football ( child ) ");
	   }
	   public void indoor_games(){
		  System.out.println("Table Tennis( child ) ");
	 }
}
Output
Cricket ( parent )
Football ( child ) 
Table Tennis( child )



Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer