• (2 Pages)
  • +
  • 1
  • 2

Abstract Classes vs. Interfaces all about Abstract Classes, Abstract methods and Interfaces Rate Topic: -----

#1 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1011
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Posted 07 October 2009 - 08:50 AM

*
POPULAR

Abstract classes, Abstract methods and interfaces

Hi all!
In that tutorial I'll explain about abstract classes, abstract methods and interfaces.
Plus, the differences between an interface and an abstract class.
Ok! lets start!

Abstract class

An abstract class is a class that is declared abstract.
It cannot be instantiated, so if you'll try running the following code you'll get an error messege:
public abstract class AbstractClass {
public AbstractClass(){//the constructor
}
public static void main(String args[]){
AbstractClass abstractClassInstance = new AbstractClass(); //Error!
}
}


However, an abstract class can be subclassed.
public abstract class AbstractClass {
}

public class SubClass extends AbstractClass{
}


After defining an abstract class, lets check why would you want to declare your class as an abstract class?
you would want to declare your class as an abstract class when your class describes an abstract idea
rather than a specific one.
Lets take an example from real life for an abstact class:
public abstract class Food{
}


Food! who doesnt like food! there are so much types of Food
but wait... what exactly is Food???? or, why did I declare Food abstract????
I'll answer that question with another question ;)
Suppose i asked you "what did you eat for lunch?"
you may answer: "I ate pizza for lunch!" or maybe "I ate Pancake for lunch!"
but you will never answer, "I ate Food for lunch!"
why? because Food is an abstract definition for "Things we eat".
while Pizza, and Pancake are subclasses of food. in code it would look something like this:
public abstract class Food {
}

public class Pizza extends Food {
}

public class Pancake extends Food {
}


You can declare instances of Pizza, and Pancake but not of food.

Ok. now, after we understood what an abstract class is, lets move to:

Abstract methods!

An abstract method is declared that way:
public abstract void abstractMethod();


Some important things concerned abstract methods:
1. Abstract method cannot be declared private!
2. Abstract methods don't have a body. these are empty methods.
so when declaring an abstract method, end the line with ";".
3.Only abstract classes can contain abstract methods!
(or interfaces, will be explained later).

Why would you want to use abstract method?
lets return to our food example.
to eat food, you have to prepare it.(cook\fry or so).
so how do you prepare Food?
there is no question for this question. why??
because each instance of food(pizza, Pancake, salad) is prepared in a different way!
public abstract class Food{
public food(){
}
public abstract void prepare();//the abstract method
}

public class Pizza extends Food {
public Pizza(){
}
public void prepare(){
//cut tomatoes, have the dough, add cheese, insert the oven...
}
}//end of pizza subclass

public class Pancake extends Food{
public pancake(){
}
public void prepare(){
//add all ingredients on the pan, add sauce, onions, fry it...
}
}//end of Pancake class


In that example you see how you use an abstract method.
abstract method should be used when you want to do the same operation, but in different ways.

After defining abstract methods and abstract classes we are ready for
the next topic.

Interfaces!

What is an interface?
Think of an interface as a contract that a class does.
in order to implement an interface a class must implement the interfaces methods.
An interface contains constants and abstract methods.(only abstract methods!).
it looks like:
public interface newInterface{//newInterface can be replaced by every name you want.
int CONST1;//can be every data type. (long,char etc...).
String CONST2;
//more constants..
void Method1();
int Method2();//can return all sort of data (long,char, boolean etc).
//more methods...
}


This is how an interface should be look like.
important!
1.notice that I don't declare the constant variables as public\private\protected.
in an interface they all get: public static.
2.notice that i dont declare the methods with public\private and also not abstract.
in an interface all methods get by default: "public abstract".
3.There is another type of interface. Marker Interfaces. marker interfaces are markers without methods. like the serializable interface.
It looks like that:
public interface serializable {
}


later on my tutorial you'll understand why will you need an empty interface????

Lets proceed, and have an example for using interfaces from the Java API.
The List interface.
A List is an interface.
ArrayList and LinkedList are classes implementin the List interface.
suppose in your code you nedd a List of String objects(could be any other data type though).
List<String> stringList = new ArrayList<String>();


Later on your code, you decide that you made a mistake, and a LinkedList is what you need.
So you just change the declaration to:
List<String> stringList = new LinkedList<String>();



When will you use an interface? why not use an abstract class?
first lets check the differences between an abstract class and an interface.
1.a certain class can extend only ONE superclass, while it can implement multiple interfaces.
2.an abstract class can contain implementation for some of its methods, while an interface only declares methods.
notice that if you declare an abstract class with only abstract methods, it should be declared as an interface!
3.an abstract class can contain all sort of variables(not only public static), and also can contain private, protected methods.

Now after understanding all basic definitions, we are ready for the main subject!

When will you use an interface rather than an abstract class?

Suppose you want to have Washable items.
who doesnt wash his stuff???
By stuff i mean your vehicle, your clothes etc.
Probably you have some kind of vehicle. right? a car? motorbike? a bicycle? rollerblades??
And i assume you wash them once a week..
And of course you have clothes you wear. (shirt, pants, jacket).
And i HOPE you wash them at least once a week!
so first declare a new class Washable:

NOTE: the following code is the wrong way to achieve our task. it is just to show why an abstract class is the wrong choice for what we want to do.
public abstract class Washable {
public Washable(){
}
public abstract void wash(){;
}


now, washing a car is different than washing a bicycle, and is definately different than washing a rollerblades. right?
also, washing colored clothes is different than washing white clothes.
so, what will you do if you want to create a car class?
public class car extends vehicle, extends Washable { //cant extend both!
}


NOTE:the end of the wrong code i mentioned before.

What you want to do in such a case is declare Washable as an interface.
public interface Washable {
void wash();
}


Now you can implement it with all these classes, and implement the wash method differently!
public abstract class Vehicle implements Washable{
public Vehicle(){
}
public abstract void wash();//wash is abstract because it is not yet implemented!
}

public abstract class Clothes implements Washable{
public Clothes(){
}
public abstract void wash();//wash is abstract because it is not yet implemented!
}

public class Car extends Vehicle {
public Car(){
}
public void wash(){
//the wash method for a car
}
}

public class Bicycle extends vehicle {
public Bicycle(){
}
public void wash(){
//the wash method for a bicycle
}
}

//now for clothes

public Shirt extends Clothes {
public Shirt(){
}
public void wash(){
the wash method for shirt
}
}

//and so on!


most important note:
When implementing an interface's method, you can't assign it different access privelege other than public.
The reason is that all methods in theare declared public. and in java you cant override a method by assign it a weaker access.

implementing the Washable interface in both Clothes and Vehicles has benefits!
Suppose you have a new Robot and you want it to wash all your stuff.
BY stuff i mean all your Clothes and all your Vehicles. (i want that robot too!)
you could have a list of Washable objects and use the wash method on all of them!
public class Robot {
public Robot(){
}
public void washAllMyStuff(){
List<Washable> objectsToWash = new ArrayList<Washable>();
//add your washable items to the list
//then go over the list and invoke wash()
for(Washable washableObject : objectsToWash){
washableObject.wash();
}
}


Of course, you can create other abstract classes like Furniture and implement Washable on those classes.
then add them to the robot's washing list!
Have i already mention how Cool that Robot is?

ok that is the end of my tutorial, where i covered abstract classes, abstract methods and interfaces.
hope it helped :)

Is This A Good Question/Topic? 30
  • +

Replies To: Abstract Classes vs. Interfaces

#2 Laythe  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 76
  • Joined: 09-June 09

Posted 06 February 2010 - 04:34 PM

Thank you very much sir Japanir for The Tutorial.
It's a clear Tutorial indeed.
Was This Post Helpful? 0
  • +
  • -

#3 pdkharkar  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 63
  • View blog
  • Posts: 345
  • Joined: 19-January 09

Posted 19 February 2010 - 06:26 AM

hahaha
nice way to explain
even I am adapting the way you are using
Was This Post Helpful? 0
  • +
  • -

#4 dipjyoti  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 20-November 10

Posted 20 November 2010 - 12:03 PM

thnax sir its a very nice explanation ........
Was This Post Helpful? 0
  • +
  • -

#5 vienhuynh  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 123
  • Joined: 24-April 10

Posted 01 March 2011 - 06:51 PM

awesome, I really appreciate it :) Great tutorial.
Was This Post Helpful? 0
  • +
  • -

#6 zalow77  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 4
  • Joined: 20-March 11

Posted 04 May 2011 - 11:37 AM

Well explained tutorial, thanks a lot :)
Was This Post Helpful? 0
  • +
  • -

#7 manpikin  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 07-May 11

Posted 07 May 2011 - 03:31 PM

This is the best explation. Hope guys get it. Thanks
Was This Post Helpful? 0
  • +
  • -

#8 stephen5huo  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 20-April 11

Posted 10 May 2011 - 09:26 AM

Very good tutorial, thx for the effort :)
Was This Post Helpful? 0
  • +
  • -

#9 v0rtex  Icon User is offline

  • Caffeine: db "Never Enough!"
  • member icon

Reputation: 223
  • View blog
  • Posts: 773
  • Joined: 02-June 10

Posted 23 May 2011 - 01:57 PM

Thanks! Interesting tutorial indeed.
Was This Post Helpful? 0
  • +
  • -

#10 nmohamma  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 26
  • Joined: 13-June 11

Posted 13 June 2011 - 04:57 AM

Great Tutorial and very easily and nicely explained :bananaman:
Was This Post Helpful? 0
  • +
  • -

#11 wingsandsky  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 05-March 11

Posted 20 June 2011 - 09:39 AM

Hi, the tutorial is nice. But why first you say "2. Abstract methods don't have a body. these are empty methods.
so when declaring an abstract method, end the line with ";"." and later you say "2.an abstract class can contain implementation for some of its methods, while an interface only declares methods". An abstract class can contain "non abstract" methods?
Was This Post Helpful? 0
  • +
  • -

#12 Niha  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 42
  • Joined: 20-April 07

Posted 27 June 2011 - 04:56 AM

Thank you very much. You explained it much better than the textbook I'm learning Java from. :balloon:
Was This Post Helpful? 0
  • +
  • -

#13 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,063
  • Joined: 28-December 10

Posted 04 July 2011 - 08:32 PM

View Postwingsandsky, on 20 June 2011 - 09:39 AM, said:

Hi, the tutorial is nice. But why first you say "2. Abstract methods don't have a body. these are empty methods.
so when declaring an abstract method, end the line with ";"." and later you say "2.an abstract class can contain implementation for some of its methods, while an interface only declares methods". An abstract class can contain "non abstract" methods?


The answer to your last question is "yes". Abstract classes contain non abstract methods. Here, let me take your hand and show you the way.

Quote

But why first you say "2. Abstract methods don't have a body. these are empty methods.
so when declaring an abstract method, end the line with ";"."


The answer is right there. The abstract method is the one he's referring to not having a body. Then the next line,

Quote

and later you say "2.an abstract class can contain implementation for some of its methods, while an interface only declares methods".


Now he's referring to the class itself.

To conclude:
Abstract classes can contain concrete methods with implementations, but
Abstract methods can't contain implementations. It's up to the subclass to do it.

Hope that clears things up. Now releasing your hand, I think you can now find your own way.
:)
Was This Post Helpful? 0
  • +
  • -

#14 bvarghese2155  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 13-August 12

Posted 11 September 2012 - 10:05 PM

if the vehicle class implemented the Washable interface, why does it need to write the wash() again???

also, random question about ArrayLists...... can different objects (strings and longs for example) be stored in an ArrayList and then be displayed on the screen? Why use an ArrayList instead of an array?
Was This Post Helpful? 0
  • +
  • -

#15 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,063
  • Joined: 28-December 10

Posted 11 September 2012 - 11:06 PM

Hey there. Once you extend an abstract class you need to write the implementation for those abstract methods which have no implementation on the abstract class. Those that have an implementation on the abstract class can be left as is. You can override them too, if you like.

ArrayLists can change size according to your need. They grow bigger and bigger and you can put in stuff at an ArrayList without thinking about declaring a new array with a new size just to add another element.

By the way by storing Strings and longs do you mean different objects in one collection? Yes, it is possible but you must find something that binds them together, like a similar Interface or class, in this case, the Object class. It would be tricky to print them though in one go.

Others, any thoughts?
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2