Sunday, July 1, 2018

Method overriding facts

# Rules for method overriding #

1. Name, parameter list, and return type must be same.

note: different parameter list will lead into method overloading inside subclass, but different return type is a compiler error (error during compilation time).

example:

class Parent
{
void eat()
{
}
}

class Child extends Parent
{
// this is a valid overriding
void eat()
{
}
}

# # # # # # # # # # # #

class Parent
{
void eat()
{
}
}

class Child extends Parent
{
// different parameter list
// so it is a overloading
// now subclass has two copies of
// eat methods
void eat(int x)
{
}
}



2. The final or private or static methods of super-class cant be override  by the subclass.

example:

class Parent
{
// this method cant be override by
// the subclass
final void eat()
{
}
}

class Child extends Parent
{
// this is a compiler error
// cant override the final method
void eat()
{
}
}

3. The accessibility of super-class method should be same in subclass, or can be increased. But it cant be decreased in subclass, public is a best practice 

example:

class Parent
{
        // this is a package private method
void eat()
{
}
}

class Child extends Parent
{
        // here i am providing public accessibility during overriding 
       public void eat()
{
}
}

# Benefits of method overriding #

Using overriding a subclass can change the behavior of super-class's method.
Then the super-class can access that changed behavior using polymorphic assignment.
This process is known as dynamic method dispatch (runtime polymorphism)

example:

class Father
{
void eat()
{
System.out.println("lets eat rice");
}
}

class Son extends Father
{
void eat()
{
System.out.println("lets eat pasta");
}
}

class Test
{
public static void main(String[] args)
{
// lets do a polymorphic assignment
// bole toh reference variable super-class ka
// but object uski subclass ka
Father f = new Son();

// now the Father will call the method of Son
f.eat(); // output will be ------> 'lets eat pasta'
}
}


2 comments:

  1. great way of explanation .......
    thank you sir for providing such kind of useful information...😊

    ReplyDelete