Pages

Friday 21 September 2012

Interface in java ?

The one which is having all the methods abstract in it .

 Any subclass which is implementing the interface
should implement all of its methods to become concrete class otherwise it should become abstract class.

interface = 100% pure abstract class.

about members of an interface

1) All the members are public by default. and it should be public only(means we cant make private or protected).

2)The variables are static and final by default.

3)The methods are abstract by default.(method implementation inside the interface is not not not possible).


Rules to remember -

1)Interface variables are public static and final

2)Interface methods are public abstract .

3)We cant modify the above 2 rules so it is good to remember those rules.

Why interface ?
To achieve multiple inheritance.

observe the below  problem




1) To include MTECH and MBA common behaviors we have a parent class PG
but to include MTECH specific behaviors we dont have any other parent  other
than PG. So if you include them in PG they will be inherited automatically to MBA which is irrelevant to MBA.

       So how do we include MTECH specific behaviors in any super class other than PG and also MTECH should be sub class to PG and the parent which holds MTECH specific behaviors (which results in MTECH should have two parents) which is called multiple inheritance .

But  it is not supported in java. so the solution is as below

        Make one interface which is parent to MTECH class and let it have only MTECH specific behaviors
and MTECH class should implement this interface and extends  PG class.
Now MBA class extends only PG class and doesn't implement MTECH specific interface. So in that way it will not have MTECH specific behaviors inside MBA class (which are not required to MBA)
   


See the below diagram for the solution to the first diagram by making use of great concept in java
   i.e;  " INTERFACE "













No comments:

Post a Comment