I'm new, sorry if this is in the wrong place, mods please move this if necessary.

Basically, I'm trying to give a breif definition of interfaces and abstract classes, please check if these are right:

An interface defines what should be done not how it should be done. The interface class contains only methods and these methods have no concrete implementations – this is left to the classes that implement the interface. Each of the methods in the interface must be implemented in any class that implements the interface. Interfaces provide a kind of multiple inheritance because while a class can have only one superclass i.e. only one class can be extended (i.e. ‘extends’ keyword only used once), many interfaces can be implemented (by using the ‘implements’ keyword before each interface).

An abstract class provides a set of default behaviours that are available to its subclasses. Each of these default behaviours are defined in methods that are abstract, it is then left to the subclasses to give their own specialized implementations of these methods but every abstract method must be implemented in the subclasses. An abstract class does not have to have abstract methods but if a method in a class is declared abstract then the whole class must be declared abstract. Abstract classes cannot be instantiated.

Also, I'm kind of confused about when to use an interface and when to use an abstract class.


Recommended Answers

All 4 Replies

A class can have some methods with code that can be executed, an interface does not have any code.

You extend an abstract class but implement an interface. You can only extend one class, so that limits their usefulness. In general an abstract class makes most sense when it contains a larg-ish amount of code that its subclasses can inherit and use.

One more thing that I would like to add is:

a general rule in inheritance is that a subclass has an "is a" or more specifically "is a kind of" relationship in real world with its super class for example if a superclass is Shape and there are three subclases inherited from it, Circle, Triangle and Rectangle then every Triangle "is a" Shape or "is a kind of" Shape, every Circle "is a" shape and so on. So in this case, Shape should me made an abstract class and Circle, Triangle and Rectangle should be inherited from it. if a common functionality that you want in a group of your classes does not fit in the hierarchy in this way that each of those classes could be considered as "a kind of" that superclass in the real world than you should instead consider making it an interface and implement this interface in those child classes.

What you guys think? Am I right in stating this??

I say "Yes".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.