Interfaces and Abstract Classes

Interfaces and abstract classes are used within object orientated programming to extend other classes and add additional functionality without rewriting or duplicating code. The difference between interfaces and abstract classes when compared to creating a normal base class is that you cannot instantiate an interface or abstract class. If you create an abstract class called ‘Animal’ you then cannot create a new instance of an Animal.

The below code defines an interface called ‘CanTalk’ that has one method called ‘talk’. Due to it being an interface we do not define the body of the method, as that is defined within classes that inherit from this interface. The talk method return a String type variable, so any class that inherits from this interface must return a String variable when filling out the body of this method.

The below code defines an abstract class called ‘Animal’. This class has one private field called ‘name’ that is a String data type, one getter method that returns this field. A field is pass into the constructor of this class, and assigned to the internal variable called ‘name’. As this is an abstract class an instance of an Animal cannot be created. All of the fields, methods, and constructor arguments are inherited when a child class inherits from the Animal class.

The ‘Dog’ class inherits from the ‘Animal’ abstract Class and the ‘CanTalk’ interface. The Dog class must pass a variable to the super constructor, defined within the Animal class. We must also define the body of the ‘talk’ method define in the ‘CanTalk’ interface, due to inheriting from that interface.

Now we can use our ‘Dog’ class to create an instance of the class and assign it to a variable called ‘fido’. The fido variable gives the string value “Fido” to the name field. The fido variable can call both the ‘getName’ and ‘talk’ methods, due to the inheritance structure explained above.

Polymorphism applied to interfaces and abstract classes too. We can declare a variable type of an abstract class, such as Animal, or of an interface, such as CanTalk. However, when we initilise the variable it must be a concreate class (not an interface or abstract class). Also, an object can only call methods and access fields that exist within the declared type. In regards to the below code, the ‘buddy’ variable can only access things defined inside the ‘Animal’ abstract class and the ‘duke’ variable can only access methods decalred within the ‘CanTalk’ interface. Remember, the declared variable type is on the left of the equaLs ‘=’ symbol and the initilised variable type is on the right side of the equals ‘=’ symbol.

One thought to “Interfaces and Abstract Classes”

Leave a Reply