Lesson 17 - Interfaces in Java

Java OOP Interfaces in Java

In the previous lesson, Diary with a database in Java (finishing), we practiced working with List collections and created an electronic diary in Java. In today's tutorial, we'll be getting back into some more theoretical matters. We're going to unveil yet another utility of the object-oriented programming world!

Interface

When one refers to an object's interface, they are referring to how an object is visible from the outside. We already know that an object contains methods that can be set as private or public. The object's interface consists of its public methods, which are the main ways we communicate with certain types of objects. We have already dealt with public methods in previous lessons, e.g. the ones we set up for our arena warrior. The Warrior class we made had the following public methods:

  • void attack(Warrior enemy)
  • void defend(int hit)
  • boolean alive()
  • void setMessage(String message)
  • String getLastMessage()
  • String healthBar()

If we store an instance of the Warrior class into a variable, we would be able to call the attack() or defend() methods on it. Nothing new, right? As a matter of fact, we are able to declare an interface separately, sort of like we do with classes, and we would then be able to use it as a data type.

We'll give it a go, but on a simpler class than the Warrior class we made. We'll start by creating a new project, naming it InterfaceSample, and adding a simple class. In my opinion, theoretical concepts should be explained using light examples, meaning not as serious. With that all being said, let's make a bird class! Our bird will be able to chirp, breathe and peck. Our Bird class will look something like this:

public class Bird {

        public void chirp() {
                System.out.println("♫ ♫ ♫");
        }

        public void breathe() {
                System.out.println("Breathing...");
        }

        public void peck() {
                System.out.println("Peck, peck!");
        }

}

Done! Now, let's move to InterfaceSample­.java and create an instance of the bird:

Bird bird = new Bird();

Once you've created an instance of the bird class, write whatever you called the instance, in my case, it is "bird", and add a dot right after it. NetBeans will then display all of its class methods (you can also invoke this menu by pressing Ctrl + Space):

Bird methods in Java

We now see everything that we can call on the bird instance. The 3 methods we just now implemented are there as well as some others that all objects have from its base.

Now let's create an interface for our bird. We'll use the interface keyword to do just that. Right-click on the project, and choose New -> Java Interface.

New interface in NetBeans

An empty interface will be added to our project. We'll add headers of methods which this interface will require. The implementation itself, method content, is added by the class that implements the interface.

Let's add method headers to the BirdInterface, we'll purposely omit one of them and only add chirping and breathing:

public interface BirdInterface {
        void chirp();
        void breathe();
}

We don't specify the public modifier since an interface exclusively contains public methods. It wouldn't make sense otherwise since it indicates how to work with an object from the outside.

Let's go back to InterfaceSample­.java and change the line with the bird variable so it won't be longer of the Bird type, but of the BirdInterface type:

BirdInterface bird = new Bird();

What the code above means is that in the bird variable, we expect an object that contains the methods specified in the BirdInterface interface. NetBeans reports an error since the Bird class doesn't implement BirdInterface yet. Although it does have the needed methods, it must first be instructed to implement the interface. Let's move to the Bird class and allow it to implement the BirdInterface interface. We do it using the implements keyword:

public class Bird implements BirdInterface {
 . . .

When we go back to InterfaceSample­.java, the line with the variable of the BirdInterface type no longer throws an error. The Bird class correctly implements the BirdInterface interface. Meaning that Bird instances can now be stored in variables of this type.

Now just for completeness' sake, let's see what happens when we remove a method from the class, which is required by the interface, like the chirp() method. NetBeans will warn us that the implementation is not complete. Once you have visual confirmation of the interface's dependency on the class, put the method back where it belongs.

Let's write bird with a dot after it. Again, NetBeans will offer the following methods:

Methods of a bird stored in a variable of the BirdInterface interface

We can see that now we can call only the methods provided by the interface on the instance. That's because the bird is now a variable of the BirdInterface type, not the Bird type. Meaning that we cannot call the peck() method because we did not add it to the interface.

Why did we leave it out in the first place, you may ask? Lots of potential reasons, we've already encountered one of them. By using an interface, we simplify a complex object and expose only the parts needed in a certain part of the program.

Also, I must add that interfaces cannot be instantiated. In other words, this code will not work:

// this code won't work
BirdInterface bird = new BirdInterface();

Multiple inheritance

Java, like most programming languages, doesn't support multiple inheritance. Meaning that we can't inherit one class from more than one other class. Mainly, because method naming collisions could very well occur when multiple classes that containing methods with the same name inherit their methods into another class. Multiple inheritance is often worked around using interfaces because we are allowed to implement as many interfaces in a class as we want. A class of the sort only allows us to work with its instances in ways that we want to. We wouldn't have to worry about object type it actually is, or what it provides beyond the interfaces.

Now let's add a LizardInterface to our project. It will be able to breathe and crawl:

public interface LizardInterface {
        void crawl();
        void breathe();
}

Next, we'll apply "multiple inheritance", more accurately, implement multiple interfaces using a single class. We'll add a Pterodactyl.java class to the project. It will implement BirdInterface and LizardInterface interfaces:

class Pterodactyl implements LizardInterface, BirdInterface {
}

If we click on a "light-bulb" icon, we can choose to Implement all abstract methods. NetBeans will then automatically generate the necessary class methods.

Automatic interface implementation in NetBeans

After having implemented both interfaces, the code will look like this:

class Pterodactyl implements LizardInterface, BirdInterface {

        @Override
        public void crawl() {
                throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public void breathe() {
                throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public void chirp() {
                throw new UnsupportedOperationException("Not supported yet.");
        }
}

Notice that NetBeans has added the @Override annotation to methods implementing the interfaces. It's more clear this way so we'll add the same annotation to the chirp() and breathe() methods in the Bird class as well.

Now all we have to do is specify what we want each method to do:

@Override
public void crawl() {
        System.out.println("I'm crawling...");
}

@Override
public void breathe() {
        System.out.println("I'm breathing...");
}

@Override
public void chirp() {
        System.out.println("♫ ♫♫ ♫ ♫ ♫♫");
}

That's pretty much it! Now, let's add an instance of the Pterodactyl class in InterfaceSample­.java:

Pterodactyl pterodactyl = new Pterodactyl();

Make sure, that it has both the bird and lizard methods:

Bird and lizard methods on a pterodactyl instance

We'll stick to interfaces for a little while since there is much more to them that we haven't covered. In the next lesson, Type casting and object hierarchy in Java, you will learn more advanced techniques in object-oriented programming.


 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
1 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Activities (4)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!