43

I know the syntax, rules applied to abstract class and I want know usage of an abstract class

Abstract class can not be instantiated directly but can be extended by other class

What is the advantage of doing so?

How it is different from an Interface?

I know that one class can implement multiple interfaces but can only extend one abstract class. Is that only difference between an interface and an abstract class?

I am aware about usage of an Interface. I have learned that from Event delegation model of AWT in Java.

In which situations I should declare class as an abstract class? What is benefits of that?

5
  • 14
    This has been asked, you know. A search will turn up other questions like this one. You should start on Google, which will lead you to Stack Overflow. All of these are duplicates: stackoverflow.com/search?q=abstract+interface.
    – S.Lott
    Jul 29, 2011 at 9:53
  • 1
    "usage of Abstract class they just discuss ... rules". What? What's different between "rules" and "usage"? Your exact question was asked, by the way. I know. I answered it. Keep looking. It's important to learn how to use search.
    – S.Lott
    Jul 29, 2011 at 11:17
  • I mean "In which situations i should declare class as abstract class? what is benefits of that?" Jul 29, 2011 at 11:23
  • An interface is a pure abstract class, that is all. They are one in the same. I use abstract class all the time for a function in the base class that cant be implemented because it needs data that only the subclasses have, but I want to ensure that every subclass has this function and implements it accordingly.
    – AngryBird
    Jul 29, 2011 at 15:01
  • I find the template method pattern a very powerful one and a good use-case for abstract classes.
    – Random42
    Apr 14, 2014 at 6:09

9 Answers 9

57

This answer does a good job of explaining the differences between an abstract class and an interface, but it doesn't answer why you should declare one.

From a purely technical standpoint, there is never a requirement to declare a class as abstract.

Consider the following three classes:

class Database { 
    public String[] getTableNames() { return null; } //or throw an exception? who knows...
}

class SqlDatabase extends Database { } //TODO: override getTableNames

class OracleDatabase extends Database { }  //TODO: override getTableNames

You don't have to make the Database class abstract, even though there is an obvious problem with its implementation: When you are writing this program, you could type new Database() and it would be valid, but it would never work.

Regardless, you would still get polymorphism, so as long as your program only makes SqlDatabase and OracleDatabase instances, you could write methods like:

public void printTableNames(Database database) {
    String[] names = database.getTableNames();
}

Abstract classes improve the situation by preventing a developer from instantiating the base class, because a developer has marked it as having missing functionality. It also provides compile-time safety so that you can ensure that any classes that extend your abstract class provide the bare minimum functionality to work, and you don't need to worry about putting stub methods (like the one above) that inheritors somehow have to magically know that they have to override a method in order to make it work.

Interfaces are a totally separate topic. An interface lets you describe what operations can be performed on an object. You would typically use interfaces when writing methods, components, etc. that use the services of other components, objects, but you don't care what the actual type of object you are getting the services from is.

Consider the following method:

public void saveToDatabase(IProductDatabase database) {
     database.addProduct(this.getName(), this.getPrice());
}

You don't care about whether the database object inherits from any particular object, you just care that it has an addProduct method. So in this case, an interface is better suited than making all of your classes happen to inherit from the same base class.

Sometimes the combination of the two works very nicely. For example:

abstract class RemoteDatabase implements IProductDatabase { 
    public abstract String[] connect();
    public abstract void writeRow(string col1, string col2);

    public void addProduct(String name, Double price) {
        connect();
        writeRow(name, price.toString());
    }
}

class SqlDatabase extends RemoteDatabase {
    //TODO override connect and writeRow
}

class OracleDatabase extends RemoteDatabase { 
    //TODO override connect and writeRow
}

class FileDatabase implements IProductDatabase {
    public void addProduct(String name, Double price) {
         //TODO: just write to file
    }
}

Notice how some of the databases inherit from RemoteDatabase to share some functionality (like connecting before writing a row), but FileDatabase is separate class that only implements IProductDatabase.

0
16

Similarities

Abstract classes and interfaces are required for the abstraction. They cannot be instantiated with a new, but are possible to be resolved to in inversion of control containers or via factory patterns.

Difference

  1. Interfaces

    • Define well known public contract, abilities of the type
    • Applicable to show horizontal inheritance, i.e. branching on the first level of inheritance (e.g. ILog to define logging facilities to database, text file, XML, SOAP etc.)
    • All members are public
    • No implementation allowed
    • Inheritance child can have many interfaces to implement
    • Useful for third party integration
    • Naming usually starts with I
  2. Abstract class

    • Define structure, identity and some default supported behaviour
    • Applicable to show vertical inheritance, i.e. deep branching on the several levels (e.g. AbstractEntity class in domain driven development)
    • Members can have different visibility (from public to private)
    • You can implement some members (e.g. *Reader classes)
    • Inheritance child can have only one base abstract class

It is actually easy to find the answer by simple google query.

2
  • what do you mena by implementation not allowed? java class can implement interfaces.
    – Sajuuk
    Jul 5, 2018 at 11:26
  • @Sajuuk that line refers to an interface. You cannot put implementation of a contract into an interface. You may have default implementation of a contract in an abstract class.
    – oleksii
    Jul 9, 2018 at 11:26
11

How it is different from an Interface?

In an abstract class, you can implement some methods, and leave (force) the rest to be implemented by the extending class. You can't implement methods in an interface. You can't force anyone to override anything when extending an ordinary class. With an abstract class, you can.

1
  • This really needs an update for Java 8, where default methods were introduced. May 6, 2017 at 20:20
8

Abstract classes are for "is a" relationships and interfaces are for "can do".

Abstract classes let you add base behavior so programmers don't have to code everything, while still forcing them to follow your design.

3

Besides the deep technical details - like implementation of some methods for abstract classes, etc., the meaning is like this:

Interfaces define common capability - IEnumerable defines, that the class which implements this interface can be enumerated. It does not say anything about the class itself.

Abstract (or base) classes define behavior - WebRequest defines a common behavior of all child classes like HttpWebRequest, etc. It defines the core meaning of the class and it's real purpose - to access web resources.

2

Wikipedia entry.

The main differences between an interface and an abstract class is that an abstract class may provide implemented methods. With interfaces you can only declare methods, write their signature. Here is an example of an class that extends an abstract class that implements two interfaces: (java)

interface MyInterface1 {
  string getValue1();
}

interface MyInterface2 {
  string getValue2();
}

abstract class MyAbstractClass implements MyInterface1, MyInterface2{
  void printValues() {
    System.out.println("Value 1: " + getValue1() + ", Value 2: " + getValue2() + 
                       ", Value 3: " + getValue3());
  }

  protected abstract string getValue3();
}

class ImpClass extends MyAbstractClass {
  public string getValue1() {
    return "1";
  }

  public string getValue2() {
    return "2";
  }

  protected string getValue3() {
    return "3";
  }
}

In this example, the MyAbstractClass provides a public method that prints all three values. In ImpClass you need to implement getValue1, and getValue2 respectively from MyInterface1 and MyInterface2 and getValue3 from the abstract class.

Voilà.

There are more aspects (interface: only public methods, abstract class: protected abstract and public abstract methods) but you can read that for yourself.

On a final note, an abstract class that only provides abstract methods is a "pure" abstract base class, aka, an interface.

2
  • Interface -- when a few classes share an API (method names and parameters)
  • Abstract class -- when a few classes share same code (implementation)

In other words, you should start with a question: "do these classes necessarily share the implementation, or do they just have a common interface?"

If the answer is mixed, such as -- these three classes must share the implementation, but these other two only share their API -- then you can make an interface for all five of them, and an abstract class for those three with the common code.

There are also other ways to share implementation, for example to encapsulate an object with that implementation (e.g. in Strategy pattern).

1

You would declare a class abstract when you don't want the developer (probably yourself) to be allowed to instantiate it, because it wouldn't work or wouldn't make sense.

For example, consider a game where there are different types of game entities. They all inherit from the base GameEntity class.

abstract class GameEntity{

    int lifePoint, speed, damage;

    public attack(GameEntity target){ target.damage(damage); }

    public damage(int damageInflicted){ lifePoint -= damageInflicted - speed; }

    // etc...

}

This class is declared abstract since it wouldn't make sense to instantiate it. It declares some actions for the game entities and some attributes, but nowhere in this class are these attributes initialized. This class serves as a template for the game entities, but isn't meant to be instantiated on it's own, and as such declared abstract.

Regarding the difference in usage between an abstract class and an interface:

As I see it, an interface is a way to gain polymorphic behavior without being limited by some languages' single-inheritance mechanism.

Let's return to the game as an example. Consider a class Enemy which is derived from GameEntity. This class has a method attackMeFromDistance(RangedAttacker attacker). This method is meant to allow entities to attack the enemy from far away.

As you can see, this method takes a RangedAttacker type as a parameter. However, all of the game entities already inherit from GameEntity. They can't extend another class.

Take the classes Mage and Archer for example. We want to allow both of them to be accepted as parameters in the attackMeFromDistance(RangedAttacker attacker) method, but they're already derived from GameEntity.

To solve this, we create a new interface:

interface RangedAttacker{
    public void attackFromDistance();
}

A class that implement this interface must implement the attackFromDistance() method, and thus it is ensured that it has ranged attacking capabilities. This means that the attackMeFromDistance method can now safely accept classes that implement this interface. So making Mage and Archer implement that interface solves our problem.

To me, this is the power of interfaces.

So to sum up, you would usually use an abstract class when you want to have a base class for some classes, but it wouldn't make sense to instantiate it by itself (or in a case where it has abstract methods, that have to be implemented by the subclasses, and in this case the compiler would enforce you to make the class abstract). You would use an interface to gain polymorphic behavior without being limited by the single-inheritance mechanism.

0
  1. There is chance too few methods are common to some class (business logic). And remaining methods are different. In that kind of scenarios you can implement all the common methods in one class, and declare the remaining as abstract. Then you should declare the class as abstract.
  2. Sometimes you don't allow to create the object to the class directly. That kind of class you need to declare the class as abstract.

Not the answer you're looking for? Browse other questions tagged or ask your own question.