This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Give the easiest example which differentiate  Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Give the easiest example which differentiate  "interface" and "abstract class" in Java." Watch "Give the easiest example which differentiate  "interface" and "abstract class" in Java." New topic
Author

Give the easiest example which differentiate "interface" and "abstract class" in Java.

Robby Ames
Ranch Hand

Joined: Dec 11, 2012
Posts: 45
I know the difference between "interface" and "abstract class". But could you provide me the easiest example(program) which can be built through the "interface" but not through the "abstract class".
Joe Areeda
Ranch Hand

Joined: Apr 15, 2011
Posts: 307
    
    2

Robby Ames wrote:I know the difference between "interface" and "abstract class". But could you provide me the easiest example(program) which can be built through the "interface" but not through the "abstract class".

Robby,

The thing is that you can implement multiple interfaces in a class but you can only derive from one class.

Other than that they are very similar.

Joe


It's not what your program can do, it's what your users do with the program.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7492
    
  18

Robby Ames wrote:I know the difference between "interface" and "abstract class". But could you provide me the easiest example(program) which can be built through the "interface" but not through the "abstract class".

I think it would be better (and more informative) to try and answer the question for yourself.

What would be the difference between, for example, a program that uses AbstractList instead of List? Tip: one of the things you might want to think about is what it wouldn't be able to do.

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Joe Areeda
Ranch Hand

Joined: Apr 15, 2011
Posts: 307
    
    2

My take is he is trying to figure it out himself, just looking for examples that add meaning to all the technobablle and theory one reads about.

This is one of those Java concepts that was hard to wrap my mind around. I'll discuss my understanding of it in hopes it might help your understanding as well as find holes in mine.

The concept of Multiple Inheritance is the basis of the distinction. I'm not sure of the exact reasoning but Java designers decided it was too error prone to include in the language. I agree with the decision based on my own experience of doing it wrong in C++ but am not qualified to discuss the reasoning.

Note that an abstract class is defined as a class with at least one method defined but not implemented whereas an interface cannot implement any methods.

My favorite example Interface is Comparable (http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Comparable.html) it implements only one method CompareTo and is implemented in any class you want to sort (but not write your own sort routine).

Suppose you have a class Foo and you want to sort a list of Foo objects. One way would be to have the Foo class implement the Comparable interface, create an ArrayList<Foo> called fooList and then you can just run Collections.sort(fooList).

In Java you could then derive classes from Foo and sort them also, as long as they were sorted by some attribute of the base class.

How is this different from making Comparable and abstract class and deriving from Comparable and another class? In a world where we could write bug free code, no real difference, that I know of. In a world filled with programmers like me, the main difference is simplicity and better compile time checking. That is the reason I write what I can in Java instead of C++ or Python, despite it's massive footprint and startup overhead.

Again, I don't claim to be an expert in this, just trying to further the discussion.

Joe
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7492
    
  18

Joe Areeda wrote:My take is he is trying to figure it out himself, just looking for examples that add meaning to all the technobablle and theory one reads about.

Perhaps.

This is one of those Java concepts that was hard to wrap my mind around. I'll discuss my understanding of it in hopes it might help your understanding as well as find holes in mine.

The concept of Multiple Inheritance is the basis of the distinction...

I hate to say, but it's not really about multiple inheritance. An interface is an un-implemented API - simple as that. In ANY language. It cannot be implemented.

Therefore, it describes WHAT an object does, rather than HOW it does it (for more details, check out the WhatNotHow page); and that is all you need to know as the user of an object.

Java could have just as easily made interfaces single-inheritance too, but they didn't. The fact of the matter is that it's a red herring when you're trying to define the difference between an interface and a class.

HIH

Winston
Robby Ames
Ranch Hand

Joined: Dec 11, 2012
Posts: 45
Here only Winston Gutkowski understood my question. But still, I haven't got the answer. I just want a 'simple and easy to understand' answer in the term of code. As I already mentioned "I know the difference between Interface and Abstract Class".
Joe Areeda
Ranch Hand

Joined: Apr 15, 2011
Posts: 307
    
    2

Winston Gutkowski wrote:
I hate to say, but it's not really about multiple inheritance. An interface is an un-implemented API - simple as that. In ANY language. It cannot be implemented.


Since I seem to be the most confused person in this thread allow me to wallow around the muck in brain in hopes of enlightenment.

Well, isn't a pure abstract class also an unimplemented API? And an (impure) abstract class a partially implemented API. It seems to me, and I admit I'm confused, the practical difference in Java is related to multiple inheritance. Although I do agree that is not the defining difference.

when you're trying to define the difference between an interface and a class.

And just to be clear. Aren't we talking about an interface and pure abstract class?

For Robby how about this:
Joe Areeda
Ranch Hand

Joined: Apr 15, 2011
Posts: 307
    
    2

I reread my post and it may sound like I think I have a good handle on this.

I don't.

I really just want to explore my conceptualization of these language constructs, hoping for a better understanding.

Joe
Robby Ames
Ranch Hand

Joined: Dec 11, 2012
Posts: 45
Joe, you're still missing the point. You can consider my question like this: "A program which can be implemented through Interface 'only' but not through Abstract Class in 'anyway'".
Joe Areeda
Ranch Hand

Joined: Apr 15, 2011
Posts: 307
    
    2

Robby Ames wrote:Joe, you're still missing the point. You can consider my question like this: "A program which can be implemented through Interface 'only' but not through Abstract Class in 'anyway'".


I think I understand your question.

As far as I know you have to come up with a scenario where you'd need to derive from one class but also need to use an interface.

I did have a situation where I had multiple windows derived from JFrame opened, which I wanted to tile in a specific order. They were stored in an ArrayList and implemented the Comparable so I could sort them in order with the Collections.sort.

In this case i had to derive from JFrame because it did so much work for me. If Comparable were an abstract class, I couldn't use it and would have to implement my own sort.

Does that help at all?
Robby Ames
Ranch Hand

Joined: Dec 11, 2012
Posts: 45
Joe Areeda wrote:

As far as I know you have to come up with a scenario where you'd need to derive from one class but also need to use an interface.

I did have a situation where I had multiple windows derived from JFrame opened, which I wanted to tile in a specific order. They were stored in an ArrayList and implemented the Comparable so I could sort them in order with the Collections.sort.

In this case i had to derive from JFrame because it did so much work for me. If Comparable were an abstract class, I couldn't use it and would have to implement my own sort.

Does that help at all?


Thanks!! Joe, Yup! you really hit the point.. But, I just want a simple example(in the terms of code) which is easy to explain(even to the beginners).
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7492
    
  18

Robby Ames wrote:Joe, you're still missing the point. You can consider my question like this: "A program which can be implemented through Interface 'only' but not through Abstract Class in 'anyway'".

Sorry guys, but I think you're both missing the point (at least from what I've read).

The whole point about an interface (again, in any language that allows it; even if they don't call it an "interface") is that it is NOT (and cannot be) implemented, except by an implementing class. It is not something that was dreamt up by the designers of Java.

The simplest piece of code I can think of to illustrate the difference - and a common mistake made by many Java newbies - is the difference between:
ArrayList<String> strings = new ArrayList<String>();
and
List<String> strings = new ArrayList<String>();

It may not seem like much, but the second version is far more flexible than the first, because it makes no assumptions about what kind of list is being assigned (ie, HOW it is implemented), it simply says: "'strings' is a List of Stings".
If you decide, later on, that a LinkedList would be better, all you need to do is change the assignment. With the first version, you would also probably have to change the code that uses 'strings'.

@Robby: That's as simple as it gets. For an entire program that uses both, you'd need to look elsewhere, and I doubt whether it would help you any more, because what you need to understand is the fundamental difference between the two.

Interface == WHAT; Class == HOW
and in general - unless you're the poor slob that actually has to write it - the WHAT is much more important than the HOW.

And even if you are that poor slob, you'd better know the first before you start writing the second.

Winston

Joe Areeda
Ranch Hand

Joined: Apr 15, 2011
Posts: 307
    
    2

Winston Gutkowski wrote:
Robby Ames wrote:Joe, you're still missing the point. You can consider my question like this: "A program which can be implemented through Interface 'only' but not through Abstract Class in 'anyway'".

Sorry guys, but I think you're both missing the point (at least from what I've read).

The whole point about an interface (again, in any language that allows it; even if they don't call it an "interface") is that it is NOT (and cannot be) implemented, except by an implementing class. It is not something that was dreamt up by the designers of Java.

Winston,
An abstract class cannot be implemented either except through an extending class.


The simplest piece of code I can think of to illustrate the difference - and a common mistake made by many Java newbies - is the difference between:
ArrayList<String> strings = new ArrayList<String>();
and
List<String> strings = new ArrayList<String>();

It may not seem like much, but the second version is far more flexible than the first, because it makes no assumptions about what kind of list is being assigned (ie, HOW it is implemented), it simply says: "'strings' is a List of Stings".
If you decide, later on, that a LinkedList would be better, all you need to do is change the assignment. With the first version, you would also probably have to change the code that uses 'strings'.


Again I fail to see what in your example depends on List being an Interface rather than a Class. If we look at the ArrayList documentation we see it is declared as:

So we could just as easily write code like
AbstractList<String> strings = new ArrayList<String>();
or go further up the class hierarchy and write
AbstractCollection<String> strings = new ArrayList<String>();

Both AbstractList and AbstractCollection are abstract classes not interfaces.

I agree with the point that declaring our objects as far up the class hierarchy as possible provides useful flexibility. The decision of which class to use is based on where the methods we need are defined not implemented but I fail to see any distinction between abstract classes and interfaces.


@Robby: That's as simple as it gets. For an entire program that uses both, you'd need to look elsewhere, and I doubt whether it would help you any more, because what you need to understand is the fundamental difference between the two.

Interface == WHAT; Class == HOW
and in general - unless you're the poor slob that actually has to write it - the WHAT is much more important than the HOW.

And even if you are that poor slob, you'd better know the first before you start writing the second.

Winston



I feel the WHAT/HOW dichotomy is just as applicable to abstract classes as it is to interfaces. I read the link you provided, thank you. While I generally agree with concept I found it a bit pedantic. <deleted a bunch of technobablle irrelevant to this discussion> I think another thread on design philosophy would be fun and enlightening.

Joe
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7492
    
  18

Joe Areeda wrote:An abstract class cannot be implemented either except through an extending class.

Of course it can. Indeed they are often used to provide partial implementations, as in the case of your own example: AbstractList. What they can't be is instantiated without a concrete class.

Again I fail to see what in your example depends on List being an Interface rather than a Class. If we look at the ArrayList documentation we see it is declared as:

So we could just as easily write code like
AbstractList<String> strings = new ArrayList<String>();
or go further up the class hierarchy and write
AbstractCollection<String> strings = new ArrayList<String>();

Well, the first one restricts you to only allowing Lists that extend AbstractList, which seems rather pointless; and the second one is just plain wrong, because you're not even going to be able to access the methods specific to a List.

I feel the WHAT/HOW dichotomy is just as applicable to abstract classes as it is to interfaces...

Again, no it isn't - indeed, they (abstract classes) are often a refinement of the HOW, because you're deciding how you're going to break it down structurally. It is however true that many interfaces lend themselves to skeleton implementations via an associated abstract class (cf, List and AbstractList).

HIH

Winston
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37907
    
  22
No, if you declare it as AbtractCollection, you can only use the methods in AbstractCollection, so you can’t use, for example get(). The idea is that the interface defines the publically‑available functionality and declaring a reference of type List tells the compiler that you are using the public functionality from that interface.
It just so happens that AbstractList implements List, so you can get away with breaching the usual practice of declaring the reference of the type of the interface. The fact that you can get away with it does not imply it is a good thing. You will come across classes which do not have such abstract counterparts, ResultSet for example, so you need to declare references by the interface name.
Joe Areeda
Ranch Hand

Joined: Apr 15, 2011
Posts: 307
    
    2

My example seems to have created more confusion than clarity. I apologize.

What I was trying to demonstrate is that when you declare a object using something up the class hierarchy it doesn't matter if it's a class (abstract or not) or an interface.

Yes, by going up the class hierarchy you are limiting functionality but gaining generality.

For example if my method only needs an Iterator, passing it (declaring) an AbstractCollection allows me to accept any implementation of List, Tree, Queue, Set or anything else derived from AbstractCollection.

What I thought we were discussing here is the difference between an abstract class and an interface. In the case of how we declare an object, I don't see a difference if the implemented class extends another class or implements an interface

Sorry for the confusion.

Joe
Robby Ames
Ranch Hand

Joined: Dec 11, 2012
Posts: 45
Thank You Everyone. Especially Joe and Winston. Thanks! Again.
Tony Docherty
Bartender

Joined: Aug 07, 2007
Posts: 2165
    
  47
For example if my method only needs an Iterator, passing it (declaring) an AbstractCollection allows me to accept any implementation of List, Tree, Queue, Set or anything else derived from AbstractCollection.

If your method just needs an Iterator then you declare your method as taking an Iterator you don't go up the class hierarchy until you find the first class that implements the Iterator Interface. That way your method can take a reference to an object from any class that implements Iterator and not just an object from the AbstractCollection hierarchy.
Jayesh A Lalwani
Bartender

Joined: Jan 17, 2008
Posts: 2271
    
  28

The way I think of Interfaces and Abstract classes is that Classes describe what a real life entity is, whereas Interfaces describe what a real life entity does. Interfaces describe behavior; Classes describe state.

SO for example, let's say you are modeling a very rudimentary tree of life . Your class hierarchy might look like this



So, Verteberate is an abstract class where you put the code that is common for all verteberates. Birds class is abstract and has the behavior for all birds. Mammal has common behavior for all Mammals. Eagle describes eagle, Ostrich describes Ostrich, and so on

Ok, but here's the hitch. Eagles can fly. Ostriches cannot fly. Dolphins can swim. Pigs can't swim . Eagles, DOlphins are carnivores. Ostriches are herbivores. Pigs are Omnivores. You can't really put the behavior in the base class. You can't say that all Birds can fly (even if most do). So, how can an Eagle class can say that it can fly, and Ostritch class say that it can't? Yes you can do some sort of hack like throw an exception from Ostritch.fly that indicates that the Ostritch cannot fly

A much more elegant way of doing this is to use Interfaces to describe behavior, and then each class can implement the interfaces for the behavior that best suit that class

So, you can have 4 interfaces Flyer, Swimmer, MeatEater, PlantEater
THen you have
Eagle extends Bird implements FLyer, MeatEater
Ostritch extends Bird implements PlantEater
Pig extends Mammal implements MeatEater, PlantEater
Dolphin extends Mammal implements Swimmer, MeatEater

Now, you can have a list of all these verteberates, and you want to find anything that flies, you just iterate over it and do instanceof FLyer to find whether it flies or not. You can make them fly by calling the fly method

A lot of people know the distinction between a IS A relationship and HAS A relationship. The former is inheritance, the latter is encapsulation. However, there is another relationship that is important, which I call the DOES relationship. If class A does X, then X should be an interface.
Robby Ames
Ranch Hand

Joined: Dec 11, 2012
Posts: 45
Thanks! Tony, Thanks! Jayesh.. Thank you Everyone..
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Give the easiest example which differentiate "interface" and "abstract class" in Java.
 
Similar Threads
Difference between Implementation Inheritance and interface inheriatance?
Interface
Question about class and interface inheritance.
When to choose abstract class and interface
How can I render all objects in an arraylist?