• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 594
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Rancher
Posts: 1369
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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!
 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[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...
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
 
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks John..that was helpful.
 
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 600
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 600
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 90
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I understood John.. By behavior, interface is the best option to choose.


Thanks,
Abu.A
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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...............


 
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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...............

 
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 237
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@Embla Tingeling :- The explanation was really nice....Thanks for that
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Khalid Mehmood,
Your post was moved to a new topic.
New question belongs in a separate topic.
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.....
 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic