Monday, 10 February 2014

This is a very controversial question,and depends from person to person
do observe the program
Demo.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class A
{
    public void show()
    {
        System.out.println("Complex logic");
    }
}
class Demo extends A
{
    //just call show() and reuse its logic
    //Dont like the show(),override it
    public static void main(String args[])
    {
        //show();//non-static method cannot be called directly from static methods
        Demo d=new Demo();
        d.show();
    }
}
Explaination:-
The main motto of inheritance is code reusablity.
i.e,The child class should be able to use parent class business logic.
If not interested,the child can redefine/override the business logic
In our above example,Demo class is happily using show(),without redefining it.
The code inside show() is re-used here,and hence it is inheritance
Now observe the following program
Demo.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
interface A
{
    public void m1();
}
interface B
{
    public void m2();
}
class InterfaceDemo implements A,B
{
    public void m1(){}
    public void m2(){}
}
class InterfaceDemo2 implements A,B
{
    public void m1(){}
    public void m2(){}
}
Explaination:-
ourclass InterfaceDemo is implementing 2 interfaces,but we are forced to define the body of m1() and m2().
m1() and m2() are abstract methods,without having any logic,and in future if 10 classes implements these methods,you have to defined body 10 times.
Code reusablity is missing here,so its very hard to justify the concept as inheritance itself
Uses of Interface:
Some of the main uses of interface are
1.Used as Marker Interface(Seriablizable,Cloneable)
2.Used to define contract between 2 parties,where one party defines what has to be done(abstract methods),and other party implements them(provides body for interface)
3.Used for method hiding/ creating light object

No comments:

Post a Comment