Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • OVERRIDING IN JAVA

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 210
    Comment on it

    Overriding method is different than overloading, as in overloading of a method, their are more than one method with same name but different parameter with in same class unlike this, In overriding of a method, a method in child class(sub class) has the same name as of its parent class(super class).

    Rules of overriding a method

    • The method names must be same in this process.
    • We can only overridden a instance method if child class inherit them.
    • A method which is declared final by using final keyword can not be overridden.
    • A child class which is in a different package can only override a non-final method which are declared either public or protected.
    • we cannot overridden constructors.
    • If we are unable to inherit a method, then we cannot overridden it.

    Syntax

    class className1
    {
         // methods
         rtype1 methodName(parameter1)
         {
                 //statements
         }
    }
    
    class className2 extends className1
    {
         // methods
         rtype1 methodName(parameter1)
         {
                 // statements
         }
    }
    

    eg:-

    class Vehicle
    {
          public void move()
          {
                 System.out.println("Vehicle can move");
          }
    }
    
    class Bike extends Vehicle
    {
         public void move()
          {
                System.out.println("Bike can move fast ");
          }
    }
    
    class MethodOverridingDemo
    {
          public static void main(String args[])
          {
                  Vehicle vehObj1 = new Vehicle(); 
                  Bike bkObj = new Bike();
                  Vehicle vehObj2 = new Bike(); 
    
                  vehObj1.move();
                  bkObj.move();
    
                  vehObj2.move();   // Dynamic method dispatch
           }
    }
    

    Output

    Vehicle can move
    Bike can move fast
    Bike can move fast
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: