Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Friday, July 11, 2014

Overriding in java: a detailed overview, conditions and rules

Overriding in java: a detailed overview, conditions and rules

When a subclass has the instance method with same signature as in super class it is known as overriding.

Overriding is also known as run time polymorphism.

Signature: name of the method and parameters (including their types)

Class Example
{
                public void m1(int x, float y)
                {
                                System.out.println("Method m1");
                }
}

m1(int x, float y) -----signature

Note:

1. Only inherited method can be overridden.

2. Final method cannot be overridden.

3. The access specifiers for an overriding method can allow more, but not less, access than the overridden method.

For example, a protected instance method in super class can be made public, but not private, in the subclass.

Range from weaker to higher.
private--->default--->protected--->public

4. Return type of the sub class method must have same or sub return type of super class method return type but not sibling.

Otherwise compiler will throw an error saying return type not matched.  

5. If a super class method is throwing any exception sub class method can/can't throw the exception but vice versa is not true.

If super class method is throwing an exception, child class should also throw the same or sub exception.  Sub class method can't throw the Parent or higher exception than super class method.

Example:
class A
{
                public String ma(String[] args) throws ArithmeticException
                {
                                System.out.println("Hello World!");
                                return "";
                }
}

class B extends A
{
                public String ma(String[] args) throws Exception
                {
                                System.out.println("Hello World!");
                                return "";
                }
}



Example of overriding:

class Parent
{
                public void m1(int x, int y)
                {
                                System.out.println("Parent class M1 method");
                }
}

class Child extends Parent
{
                public void m1(int x, int y)
                {
                                System.out.println("Child class M1 method");
                }
}

class Test
{
                public static void main(String [] args)
                {
                                Parent p=new Child();
                                p.m1(10,20);
                }
}

OUTPUT:
Child class M1 method



If you run into any issue or have any doubt you can ask in comments. 

No comments: