29

I have decided to start doing small coding projects on my own that focus on code quality instead of code quantity and have a question about the use of abstract classes.

Now I know the differences between abstract classes and interfaces with the biggest one (I think) being that interface allow you to only define methods that need to be implemented by classes using the interface and abstract classes allowing you to define both method and members along with default method implementation if you so desire. My question is what the the main benefit of use an abstract class vs a normal class? The only real difference between the two that I can think of is that you can not create an instance of an abstract class. Are there any other differences between the two?

1
  • 10
    Will the downvoters please state why you downvote answers?!?!
    – jyoungdev
    Jul 6, 2010 at 21:45

9 Answers 9

24

Strictly from a design perspective, it is best to simplify things. I believe the best way to simplify things is to use a simple analogy. Let's use an analogy of birds...

Interface: use this when you want to enforce certain functions which need to be defined. e.g. IBird has a contract for ScreamLikeABird and Fly (interface functions). But you can get more specific and have an IOstrich that has a Run contract. You may also have an IHawk that has an Attack contract...etc.

Abstract: use this when you want to enforce base functions and have base properties. e.g. Avian could be a base class for birds which may have a function called LayEgg as well as propeties called Age, Species, NumberOfChicks...etc. These things don't/shouldn't change the behavior of a bird, since all birds lay eggs...etc. But not all birds sounds the same when it scream or flies the same way (some dont even fly)....etc.... hence they should be implemented via an interface(s).

3
  • 8
    The impractical animal analogy was used to help alleviate the confusion of "interface vs abstract". BTW, how impractical is any rendition of Hello World? Practicality has nothing to do with it. Besides, I can see this analogy being extremely practical in many applications and/or games. Jul 19, 2010 at 7:44
  • 10
    Not really answering the question. The question was the difference between abstract vs. normal classes, since he knew the difference between interface and abstract... Jun 26, 2014 at 14:21
  • 1
    Agree with Calin Bolea, not even close to question, author explicitly says "I understand difference between interface and abstract class" Question was about ordinary and abstract class.
    – ggat
    May 10, 2016 at 16:08
15

In addition to not being able to create instances of abstract classes, some languages may support having abstract methods in abstract classes - similar to interfaces, an abstract method will have to be implemented by the class inheriting from the abstract class.

The main benefit of abstract classes in my opinion is if there is some code that has to be shared between classes of the same type. Usually you could use an interface for this, but sometimes the functionality of such classes may overlap and you would end up with code duplication. In this case you can use an abstract class and just put the code there.

1
  • Even if a class doesn't happen to have any abstract members and created instances have well-defined behavior, it may be sensible to define the class as abstract if it doesn't contain anything that would distinguish instances from each other. For example, one could define an ImmutableList<T> base class with subclasses for ArrayBackedImmutableList<T>, ComputedImmutableList<T>, LazyImmutableList<T>, etc. While it might be possible to have base-class instances behave as a zero-item list, it would be cleaner to define a concrete EmptyImmutableList<T> class for such purpose.
    – supercat
    Jun 16, 2013 at 21:07
12

In OO world, abstract classes used to impose some design & implementation constraints. Nothing more. You never have to use abstract classes in any case. But there might be cases that you better impose those constraints. So what are them? Let's look at by comparing it's oo-counterparts.

Abstract classes vs interfaces

As you know, these are two of the primary concepts of inheritance.

Basically, interface is used just to declare that you're willing to inherit the underlying service and that's it. Contains no implementation & has no functionality. In that sense, interface is abstract. That's why it's a more a design constraint than an implementation constraint. Think of a headphone jack on a speaker. Each headphone needs to implement the jack interface (with start, stop, listen, turnDown, turnUp methods). Each headphone should override this interface to inherit the functionality that the speaker provides and implement accordingly.

Abstract classes, on the other hand, may include methods with an implementation. That's the basic difference and in that sense it may utilize reusing more than an interface. Moreover, they may contain private, protected & non-static fields which you can't via interfaces. You may force subclasses to implement some must-have functionalities with abstract methods (those without implementations). Abstract classes more agile than interfaces.

Of course not to mention, you may only extend one class in java in where you may implement number of interfaces.

Abstract classes vs regular classes

So why not to use regular classes then. What's the benefit of using abstract class? This is pretty simple. If you use abstract classes, you force the core functionality to be implemented by the children. As a developer, you don't need to remember that you should implement the essential functions. This is where abstract classes imposing design constraints over regular classes. Plus by making the class abstract you avoid that (incomplete) class to be created accidentally.

4
  • 1
    By siblings you mean child, considering that abstract will be inherited to a class making it a parent. Right ? Feb 8, 2018 at 12:44
  • 1
    @DaniyalNasir yes.
    – stdout
    Feb 8, 2018 at 12:48
  • 1
    You have just explained something to me others could not. Thanks Sep 6, 2018 at 23:50
  • Agree with Bright. This is the answer! I am surprised how eminent contributors like Al and Jani (based on their reps) have completely sidestepped the issue raised by the OP. The answer by stdout (esp. the last para) directly addresses and answers the question. Jun 2, 2020 at 22:29
3

The only reason for declaring a class as abstract is so that it can't be instantiated. There are situations where you will have common functionality that is shared between a number of classes, but by itself that common functionality does not represent an object or represents an incomplete object. In that case, you define the common functionality as abstract so that it can't be instantiated.

0
2

in my opinion abstract classes have more use in real projects as on books. some times project managers just provide the methods declaration and you have to write code for the methods without modify the core syntax provided by manager. so that is how an abstract class is use full. in simple class method define,declared and coded in same time but not in abstract classes. for ex:-

abstract class Test
{
    abstract void show();//method provided
}
class Child extends Test
{
    void show()//coding 
    {
        System.out.println("saurav");
    }
}
class main
{
    public static void main(String[] args) 
    {
    Test c = new Child();
    c.show();   
    }
}
0

Abstract Classes vs Regular Classes vs Interface. Abstract class usually supports an idea of the generalisation and to contribute from programmers to keep a quite little brain disipline by designing multi-years projects because of they when include an abstract methods have to describe an implementation that abstract methods in subling classes, however, this feature is a disadvantage for a short-time projects when a developer have a zeitnot.

0

In automotive manufacturing terms, an Interface is a spec sheet for a "car" which says it has four wheels, five seats, an engine, etc, while an Abstract Class is a partially assembled car in a crate that you have to finish off to your own requirements. E.g. Subaru uses the same exact chassis for the Impreza, Forester and XV/Crosstrek. So the chassis is the "abstract class" which has common features and functions but isn't a "car" yet. The body and interior MUST be added after the fact before you can say you've built a car. The engine is also common among all three, though you can choose to swap it out for a turbocharged version IF you wish.

-1

This might help you, Lets consider traveler who may use any type of vehicle i.e car,cycle,bike etc...
but all vehicles moves in the same way with different speed constraints so we can have one

abstract class Avehicle    
{  
        string fuel;  
        public void move()  
{  
 sysout("moving");  
}   
} 

but all vehicles breaking system is different

interface Ivehicle    
{  

        public void breakorstop();  
}  
class Traveler    
{  
  Ivehicle v; 
//Settrers and getters   
 public drive()  
{  
v.move();  
}  
public break()  
{  
v.breakorstop();  
}  
}

So finally Car or Cycle or Bike classes can extend Avehicle and can Implement Vehicle interface

-2

Abstract classes can be used to store methods in an OOP-based "library"; since the class doesn't need to be instantiated, and would make little sense for it to be, keeping common static methods inside of an abstract class is a common practice.

3
  • "In Java, you can also declare the class as final so it isn't extends-able." No you can't. abstract + final is not allowed. If your class is meant solely for static utility methods, it should probably be a final class with a private (unused) constructor. Jul 5, 2010 at 22:28
  • @Matthew Flaschen: Point taken. Thanks for the clarification. Jul 5, 2010 at 22:31
  • 1
    Static methods are not the main reason for abstract classes.
    – jyoungdev
    Jul 6, 2010 at 21:47

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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