Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • What is Overriding in Java?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 191
    Comment on it

    When a sub class inherits the properties of super class , then we can override the method of super class.
    This will acquire the properties of super class but can define its own behaviour.


    In general way, we can say the overriding means to override the functionality of existing method.


    Example:

    class A{
        public void test()
        {
            System.out.println("This is my Super Class");
        }
    }
    class B extends A{
        public void test()
        {
            System.out.println("This is my Sub Class");
        }
    }
    public class testOverride
    {
        public static void main(String a[])
        {
            A a1 = new A(); // class A reference and object 
            A a2 = new B(); // class A reference but class B object
            a1.test(); // this will execute the method in super class
            a2.test();// this will execute the method in sub class
    
        }
    }
    


    In the above program, method test() in class B override the method test() in class A, therefore when declare an reference a2 of class A, it will execute the method in class B.


    When we compile the above code, there will be not error as both the class have method as test(), but in runtime JVM will find the object a2 is of class B and will execute its own method.

 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: