When Should You Use An Abstract Class And When Should You Use An Interface In Java?

1

1 Answers

John Wright Profile
John Wright answered
An abstract class is a class created solely to be the parent class for several sub-classes and to define some common methods and attributes that the sub-classes will inherit. We will never create an object from an abstract class, it is a starting point from which we will build other classes (which can be instantiated).

For example if modelling a bank, you would create an abstract class called account, and then sub-classes such as savings account, deposit account, business account. The abstract class can have some abstract methods and some real methods, as well as some attributes.

interfaces are very similar to abstract classes, with one important difference - ALL its methods must be abstract, they have NO body, just a name, parameter list and result type. When something inherits from an interface, you must then define the body code of the abstract methods in the interface. An interface is effectively a template awaiting the addition of details. When another class implements an interface, you are saying "I am going to use all these empty methods but write my own body code for every one of them". While in an abstract class there may already be body code.

Answer Question

Anonymous