Java Keywords (Part XII): Implementing Interfaces and Extending Classes

We are up to 34 keywords covered in previous articles! That's 71% keywords covered. We have only 16 keywords to cover and I will be covering 2 of those in this article.

This article will illustrate the use of the keywords implements and extends for implementing functionality outlined in interfaces as well as extending the functionality of a class.

I suggest you start with Java Keywords (Part I) before proceeding further, if you have not read any of the previous articles in the Java Keyword series. Also, go back and read the one about Data Types. All of these articles are from September 2018. That should help you find them quickly. You can also use the "search" option at the top of this page. The series was written with natural progression in mind. Therefore, some of the keywords already covered may be used in code examples illustrated here.

Java keyword list

abstract continue for new switch
assert default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const* float native super while
Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers.

On Part V, I covered briefly what a class and an interface is in Java. However, I didn't show you how implement an interface or how to extend the functionality of a class. As you might suspect by now, that is precisely the purpose of this article. To show how to do this, I will be using the same examples I used in Part V.


public interface Pet {
  void learnTrick(String trickName);
  void doTrick(String trickName);
  void giveName(String name);
  void respondByName(String name);
  void dressUp(); // for humans to dress their pets, not for pets to dress up on their own
}
Pet interface from Part V

public class Dog {
    // Details omitted
}
Dog class from Part V

Extending a Class

I am starting with extending classes for reasons that will be very obvious shortly. To this end, I will create two additional classes that will extend the behaviors included in the "Dog" class.

public class DomesticDog {
    // Details omitted
}

public class WildDog {
    // Details omitted
}
In order to make this example more complete, we must modify slightly our "Dog" class.

public class Dog {
  public void bark() {
    System.out.println("Woof! Woof!");
  }
}
Barking is a behavior displayed (in general) in both wild and domesticated dogs. Therefore, adding this behavior to the general "dog" class makes sense. In order to avoid duplication of code, both "DomesticDog" and "WildDog" classes will extend the "Dog" class to inherit all attributes (fields) and behaviors (methods) by using the extends keyword.

public class DomesticDog extends Dog {
    // Details omitted
}

public class WildDog extends Dog{
    // Details omitted
}
Now that I have done this, objects instantiated from both of these classes will have the ability of barking, thanks to inheritance via the use of this keyword.

DomesticDog domesticatedDog = new DomesticDog();
WildDog strayDog = new WildDog();
Dog unknownDog = new Dog();

domesticatedDog.bark(); // valid behavior of DomesticDog
strayDog.bark(); // valid behavior of WildDog
unknowDog.bark() // Expected behavior of Dog objects
I won't go into more details related to inheritance, as this is already covered in another article. Inheritance is a huge, and somewhat controversial topic that requires a lot of time to discuss fully. For now, the main goal of this article with regards to the use of the "extends" keyword has been fulfilled. As shown there, this keyword can only be used in the class header and can be used to extend only one class.

Implementing an Interface

As you may recall, or in case I didn't cover this specifically, an interface is used primarily to decouple implementation details. For example, an electric outlet "hides" all kinds of details about the electricity its supplying from the appliance or device plugged to it. This is because the item itself does not care how electricity is generated so long as the correct voltage and frequency is provided. Whether the electricity is generated from coal, thermal, wind, nuclear, or petroleum sources, is immaterial to the device receiving electric service. Similarly, a class calling methods outlined in an interface, can call these methods without worrying about implementation details.

To illustrate the proper use of the keyword extends, I need to modify my "DomesticDog" class.


public class DomesticDog extends Dog implements Pet {

  public void learnTrick(String trickName) {...}

  public void doTrick(String trickName) {...}

  public void giveName(String name) {...}

  public void respondByName(String name) {...}

  public void dressUp() {...}
    
}
I have omitted the actual implementation of each of the interface methods simply because it is unimportant for this illustration. The key point here is that in order for a class to properly implement an interface, the keyword must be used in the class header, after the keyword "extends" if the class is indeed extending another class. A class can extend another class without implementing an interface. Also, a class can implement an interface without extending another class. However, if a class needs to do both, the order of these keywords must be as shown above. If the order of these keywords is reversed, it will result in a compilation error.

Putting extending classes and implementing interfaces together, we can do something like this:


Pet myPet = new DomesticDog();

myPet.bark(); // Expected behavior of Dogs
myPet.learnTrick("Sit"); // Expected behavior of Pets
myPet.doTrick("Roll over"); // Expected behavior of Pets
myPet.giveName("Wolfie"); // Expected behavior of Pets
myPet.respondByName("Wolfie"); // Expected behavior of Pets
myPet.dressUp(); // Expected behavior of Pets 

WildDog strayDog = new WildDog();
strayDog.doTrick("Roll over") // Compiling error: WildDog is not a Pet

Next up, Part XIII: Import Keyword and the Concept of Java Packages

Comments

Popular posts from this blog

Implementing Interfaces with Java Records

Customizing Java Records

Exception Handling: File CRUD Operations Example