Learn Overriding in Java


Overriding is nothing but giving the implentation to the method in the derived class.Here method signature is same. Method overriding occurs when sub class declares a method that has the same signature (name, plus the number and the type of its parameters) and return type as a method declared by one of its superclass.
Overriding is happening with in super class and sub class. Overriding is the process where the sub class changes the behavior of super class and updates it according to sub class requirement. There are some rules for method overriding.

o    Access level of the method in the sub class should be same or wider as super class method.
o   The return type and the signature of the method in sub class      should be same as super class.
o    Static method can be overriding.
o    Dynamic binding or late binding happens in method overriding.
o    Final method cannot be overridden.
o    Constructors cannot be overridden. 

Also keep in mind below points about Overriding methods:
  •  late-binding also supports overriding
  •  overriding allows a subclass to re-define a method it inherits from it's superclass
  •  overriding methods:
1.     appear in subclasses
2.     have the same name as a superclass method
3.     have the same parameter list as a superclass method
4.     have the same return type as as a superclass method
5.     the access modifier for the overriding method may not be more    restrictive than the access modifier of the superclass method
  •   if the superclass method is public, the overriding method must be public
  •  if the superclass method is protected, the overriding method may be protected or public
  •  if the superclass method is package, the overriding method may be packagage, protected, or public
  •  if the superclass methods is private, it is not inherited and overriding is not an issue
6.     the throws clause of the overriding method may only include exceptions that can be thrown by the superclass method, including it's subclasses

 Example:

class Parent
{
    int num, num1;
    Parent(int num, int num1)
    {
        this.num = num;
        this.num = num1;
    }
    void show()
    {
        System.out.println("The values in num and num1 are: " +num+" " +num1);
    }
}
class Child extends Parent  //inherited class
{
    int count;
    Child(int num, int num1, int num2)
    {
        super(num, num1);
        count = num2;
    }
    void show()
    {
        System.out.println("The values in count is: " +count);
    }
}
class OverrideDemo
{
    public static void main(String args[])
    {
        Child sObj = new Child(5, 10, 15);
        sObj.show();
    }
}
 The program will generate the following output:

     The  values in count is: 15




0 comments:

Post a Comment