aspose file tools*
The moose likes Beginning Java and the fly likes What is the real use of interface in java apart from Multiple inheritance, Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What is the real use of interface in java apart from Multiple inheritance," Watch "What is the real use of interface in java apart from Multiple inheritance," New topic
Author

What is the real use of interface in java apart from Multiple inheritance,

jacob deiter
Ranch Hand

Joined: Apr 02, 2008
Posts: 576
What is the real use of interface in java apart from Multiple inheritance,
Initially why sun-java, added the concept of interface?
Class is used for encapsulation, abstraction .


Now-a-days, interface used in may place, for different purpose.
Monu Tripathi
Rancher

Joined: Oct 12, 2008
Posts: 1369
    
    1

Have you heard of design by contract, services etc?
The answer to your question can be very subjective. There are number of books written on the subject.
Interface Oriented Design

[List of FAQs] | [Android FAQ] | [Samuh Varta]
leroy tsruya
Ranch Hand

Joined: Sep 24, 2009
Posts: 57
Hi jacob!
sometimes you want to relate classes from different hirarcey with each other.
for this example, lets take 2 classes:


there is nothing in common between these classes.
but these two classes can be washed. you can wash a vegetable, and you can wash a car. and you do it in different way.
so you can declare an interface - Washable.


then implement it on the 2 abstract classes.
now, if you have a program with both Car and vegetable objects, and you want to wash them, you could use:


hope it helped!
s.palanivel rajan
Ranch Hand

Joined: Sep 22, 2009
Posts: 40
[color =darkred] [/color]


hi..
in java multiple inheritance is not allowed..
but in many cases multiple inheritance plays the vital role... so they introduced interface as a subsidary for multiple inheritance...
interface is similar to classes..
what is the difference here is we cant define anything inside the interface..
we cant create instance for the interface..
we should define all the functions which are declared inside the interface...


With Regards,
S.Palanivel Rajan B.E.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18707
    
  40

What is the real use of interface in java apart from Multiple inheritance


I don't really agree with the title of this topic. I don't think that a "use" of interfaces is to do "multiple inheritance".

It is true that with interfaces, you can accomplish one big advantage of multiple inheritance, in that, you can have an class that IS-A many types of classes (actually interfaces)... but this is hardly multiple inheritance. There is nothing actually being inherited -- much less multiples of inheritance.


As a side note, in all the years of working in C++, I have only actually *had* to inherited multiple classes ONCE. And when I did it, I kinda knew it was because of bad design, that was out of my control. If done right, IMO, there is no need to ever use MI -- just like, when done right, there is no need to ever use the goto statement either.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Jacob:

I agree with Henry. Interfaces are not about multiple inheritance. They are about specifying contracts for behavior, or less often, for use as markers.

John.
Abhishk Gupta
Greenhorn

Joined: Oct 08, 2008
Posts: 22
Hey John/Henry,
I too have heard only about these design,contracts and markers as possible usage of Interfaces but question is: how does it help the design in practical terms.
It would be great if someone can specify it with an example and its usability.

exapmle like this will not answer my question significantly:

My question is: How does this help? It looks like an unnecessary addition.

I know, I am not right but please correct me.


There are only 10 types of people in the world: those who understand ternary, those who don't, and those who mistake it for binary.
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Abhishk:

An analogy for an interface is to think of a class using an interface as being like an electric wall outlet, and think of the implementation as the plug. The outlet doesn't care what's behind the plug, as long as it fits in the outlet. In psuedocode terms it could be written like this:

And a class that implements ElectricOutlet might look like this:

So how do you use that interface? Like this:

Of course, it doesn't have to be an appliance that you plug into an outlet. It could be a TV, or a laptop, or a lawn mower, but they all behave the same way from the outlet's point of view. So how does this apply to programming? In exactly the same way:

I just created a new (empty) List of Strings. If it turns out that ArrayList doesn't provide the right performance, and LinkedList works better, I can go back and change that line to this:

I can do this because both ArrayList and LinkedList implement the List interface, and thus they provide the same behavior (API), even though the internal implementations may be different. From the List's point of view, however, it doesn't matter what the internal workings are, just as long as the interface is there. This allows a lot of independence between classes, and allows more reuse.

Hope that helps.

John.
Abhishk Gupta
Greenhorn

Joined: Oct 08, 2008
Posts: 22
Thanks John..that was helpful.
Abubacker Siddik
Ranch Hand

Joined: Aug 12, 2009
Posts: 90
Hi John, You have done a very good explanation for Interface..Of course you are right.. but I want to add a simple question in this regard. All you have done in this example is perfectly matching for if we use a class in place of the interface. Isnt it?

Coming to my point, instead of declaring ElectricalOutlet as an interface, we can declare it as a class, it still works the way you explained.. Why do we stress to use interface declaration?? Is it the reason that we may face multiple inheritance problem with the class in later time of the project or something else? Advise me..

In the same point of view, we may create Marker Classes like "Marker Interfaces". Why do we still go for marker interface? please explain me as i am in great war with class and interface..


Abu.A

John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Abubaker:

I think you might be thinking about this the wrong way. In my example, I am stressing behavior rather than implementation. For example, let's say we did create a class hierarchy for ElectricalOutlet:

Let's say that ElectricalOutlet has a powerUp() method that gets passed to its subclasses. But outlets only provide power right? It's the device that plugs into the outlet that uses that power. What happens if they need to do something different with that power? Well, you could provide overridden and/or overloaded versions of powerUp(), but think of all the potential variations. It seems to me that letting the device figure out what to do with the power is the better way to go. This is not to say that interfaces are better than classes, only that, in this case, we're talking about behaviors (i.e., APIs), rather than implementations.

As for your second question, no marker classes don't work in the same way that marker interfaces do. Here's a hypothetical example: Let's say that for Java 1.7, Sun decides to create Widget marker, but they're trying to decide whether it should be a class or an interface. The developers arguing for a class say that it would be easy to retrofit this to all of the classes that are widgets. They just need to add a private Widget member, and a getter and setter. The developers arguing for an interface say that a Widget marker interface would need no methods, could easily be retrofitted to existing classes, and would have the benefit of Java's type system, so that implementing classes would also be Widgets. Which do you think makes more sense?

John.
Vikash Ananda
Ranch Hand

Joined: Oct 12, 2009
Posts: 32
Hi,

I have a slightly different personal opinion regarding Interfaces in Java other than multiple inheritance thing.

Whatever we do with entities in Java is done using behaviour (methods).

If we know everything of the behaviour we make concrete methods and concrete class. If we do not know some part of it we make Abstract class and let child class implement some of its behaviour. If we know nothing regarding the behaviour we declare those methods in interfaces and let implementation class define them.

Hi All,

Is my interpretation correct?
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Vikash:

I strongly disagree with that interpretation. Interfaces vs. classes has more to do with design decisions and desired behavior than whether or not you know what the methods are supposed to do. A lot of it comes down to questions like 'does a class hierarchy make sense?' and 'will I need to retrofit my desired behavior to other classes later on?'. Also, your interpretation of abstract classes is incorrect. An abstract class can have all concrete methods or all abstract methods, or some combination of the two.

A good example of all three are the collections classes. There are examples of interfaces, abstract classes, and concrete classes in action.

John.
Abubacker Siddik
Ranch Hand

Joined: Aug 12, 2009
Posts: 90
I understood John.. By behavior, interface is the best option to choose.


Thanks,
Abu.A
vijaya sankarj
Greenhorn

Joined: Nov 06, 2009
Posts: 2
Go through this program once .................
i will explain the use of interface at the end.........


interface Interf
{
void m1();
void m2();
}
class InterfaceTest implements Interf
{
public void m1()
{
System.out.println("implementation m1");
}
public void m2()
{
System.out.println("implementation m2");
}
public void m3()
{
System.out.print("YOU WONDER !!! i knew why??? i am not instatiated by interface instance i okkkk i am an instance of InterfaceTest ..... well done you understand interfac concept now");
}
public static void main(String arg[])
{
Interf i=new InterfaceTest();
i.m1();
i.m2();
InterfaceTest b = (InterfaceTest)i;
b.m3();
}
}

Now forget the INTERFACE part in my program and follow me...........it is simple..... come on scroll....................
If you want to reuse the method m1 and m2 in some other classes means , what would you do???
Way 1 : i can instantiate an object for class InterfaceTest at my class .
DISADVANTAGE : if you instantiate another object means its implicitly tells that you create an copy of InterfaceTest class. So it wont come under the category REUSE..

Way 2 : i can extend InterfaceTest in my class .......well done good but
DISADVANTAGE : If interfaceTest contains lot of methods other than m1 and m2 means you have to allocate memory for that methods also(waste na) in your class

Way 3 : USING INTERFACE >>>>>>
make m1 and m2 methods inside an interface (now see above program once again completely)

so you can accesses it from another class like extend but one small difference you are not pointing the unwanted method m3.....good luck.......

ask questions if you need clarifications...............


Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38334
    
  23
Welcome to the Ranch

I am afraid your code is difficult to read without your using the CODE button; I shall see if I can alter your post and you can see how much better it looks.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38334
    
  23
Afraid I can't improve your post because you haven't indented it. Please go back, click the "EDIT" button, indent your code, break the String literal by putting " + " and newlines in it then highlight the two classes and push CODE. Otherwise it is difficult to read.
vijaya sankarj
Greenhorn

Joined: Nov 06, 2009
Posts: 2
Sorry for the previous post.................
i think this will be easy to read...............

Go through this program once .................
i will explain the use of interface at the end.........





Now forget the INTERFACE part in my program and follow me...........it is simple..... come on scroll....................
If you want to reuse the method m1 and m2 in some other classes means , what would you do???
Way 1 : i can instantiate an object for class InterfaceTest at my class .
DISADVANTAGE : if you instantiate another object means its implicitly tells that you create an copy of InterfaceTest class. So it wont come under the category REUSE..

Way 2 : i can extend InterfaceTest in my class .......well done good but
DISADVANTAGE : If interfaceTest contains lot of methods other than m1 and m2 means you have to allocate memory for that methods also(waste na) in your class

Way 3 : USING INTERFACE >>>>>>
make m1 and m2 methods inside an interface (now see above program once again completely)

so you can accesses it from another class like extend but one small difference you are not pointing the unwanted method m3.....good luck.......

ask questions if you need clarifications...............

Lee Kian Giap
Ranch Hand

Joined: Jan 23, 2008
Posts: 213
vijaya sankarj,

I will say you have a bit confuse concept on REUSE according to the affirmation of Way 1 from you.

"vijaya sankarj" wrote:
Way 1 : i can instantiate an object for class InterfaceTest at my class .
DISADVANTAGE : if you instantiate another object means its implicitly tells that you create an copy of InterfaceTest class. So it wont come under the category REUSE..

Way 2 : i can extend InterfaceTest in my class .......well done good but
DISADVANTAGE : If interfaceTest contains lot of methods other than m1 and m2 means you have to allocate memory for that methods also(waste na) in your class

Way 3 : USING INTERFACE >>>>>>
make m1 and m2 methods inside an interface (now see above program once again completely)

so you can accesses it from another class like extend but one small difference you are not pointing the unwanted method m3.....good luck.......



When one day you go through Thinking In Java, you might consider edit your post to change the word "DISADVANTAGE".
REUSE, we have two ways in general, composition (your Way 1) and inheritance (your Way 2).
One should consider first using composition (mostly use in the way of delegation) if one is not trying to create a more specific class.
One should not just use inheritance simply because they want polymorphism, only use inheritance when one need a more specific class.
One will use inheritance when create a specific class, but should consider interface inheritance (this is the good practice of coding to interface which repeated in a lot of design post) instead of class inheritance(i.e. implementation inheritance)
So, composition is one of the way of REUSE, and this will be used often in practice by good programmer with the concept of delegation.

Before I continue, I try to demonstrate with a Wrong (in term of concept and design) way of using inheritance, and a Correct (in term of concept and design) of using composition.






Now for your Way 2, you claim that the m3 method was not allocate to memory when using the interface without the m3, do you know that the class is loaded by class loader when you instantiate it (even you using interface type reference, because you still created the object of class that implement the interface). So, can you prove your so called memory saving with Java Profiler ? and show the result.

From your code, you need to purposely perform casting just to access method m3 ... now come to another point design, pure substitution on initial design ? one will only give up pure substitution when in that case where you are force to (e.g. when changing a legacy code). However, adapter design pattern might help you on this.


When one day you go through GOF design pattern, you might consider edit your post to change it.

Now, I try to demonstrate using the above example with strategy design pattern, and you will see the combination of composition and inheritance, both use with coding to interface (or said interface inheritance is so important) brings the benefits.




In GOF design pattern, interface inheritance is the concept that use most.


SCJP 6, SCWCD 5, SCBCD 5
Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
jacob deiter wrote:What is the real use of interface in java apart from Multiple inheritance,


It's all about inheritance. Single inheritance allows you to write more flexible programs and multiple inheritance even more so.

Java has multiple inheritance but with the restriction that implementation can be inherited from one source at the most. This is why the class concept in Java has been split into two kinds of classes, the "class" which can carry implementation and the "interface" which cannot. This division makes it easier to formulate the Java inhertance model in two easy to learn and apply rules,

1. A class can inherit one class at the most, but it can inherit as many interfaces as it wishes.
2. An interface cannot inherit any class, but it can inherit as many interfaces as it wishes.

So Java has the class and the interface for pedagogical reasons mostly. What's really important is that it has inheritance at all and multiple inheritance is even better. Class, abstract class, interface, extends, implements, etcetera are just practical details. It's the inheritance that's important. It means everything.

Inheritance allows you to write code using supertype variables. It doesn't matter really whether the supertypes are classes, abstract classes or interfaces (enums are types too but they cannot be inherited so they cannot be supertypes). It's the use of supertype variables in code that makes it so flexible and general. It allows the code to work with objects of any type as long as it inherits the required supertype. And the more supertypes an object inherits with the more code can it potentialy work.

It's how one makes use of inheritance and multi-inheritance that makes the difference. Properly utilized, inheritance leads to very general and flexible and easy to change code, and that's the ultimate goal of OO. Of course you need to learn how to juggle the available language elements which supports inheritance in Java but that's no big deal really.
Vasiq Molvizadah
Ranch Hand

Joined: Dec 24, 2009
Posts: 66
@Embla Tingeling :- The explanation was really nice....Thanks for that


Human Knowledge Belongs to the World.
- Vasiq Mz
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14103
    
  16

Khalid Mehmood,
Your post was moved to a new topic.
New question belongs in a separate topic.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Anuj Harshe
Greenhorn

Joined: Sep 13, 2013
Posts: 1
Im new in java....can anyone give real usefull example of interface... Im still confuse why we require interface... I think it just increase code and complexity .... If we want different behavior then we can create different method and call it.. why we need extra code of interface... and if we want to use the same behavior then we can call that method by creating that class object... please help me with proper example of interface.....
Rohit Aggarawal
Ranch Hand

Joined: Jun 26, 2009
Posts: 39
Reason of creating interface(s), is to provide a flexibility and adaptability to new behavior at run time, to existing Apps without change. This also help to define protocol to be supported and provide one single/one Face to the external word.


SCJP 6.0
SCBCD for JEE 5

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: What is the real use of interface in java apart from Multiple inheritance,