Java: How do I call a method that implements another method in an interface?

Harry Alexander :
public interface Directory {

    public void insertEntry(Entry entry, String surname);

Let's say I have this method which is part of the Directory interface.

public void insertEntry(Entry entry, String surname) {
}

Then I create a separate class called arrayDirectory which implements the same method in Directory. How do I then call this method in the arrayDirectory class? Because I tried to call it in main but the method has to be static in order to do this and it can't be static because then it won't implement the method from the interface, and I'm not allowed to change the method signature for the methods in the interface. Please help, I don't know what to do.

Basil Bourque :

implements

Define your class as implementing that interface. Use the keyword implements.

Also, in Java conventions, class names start with an uppercase letter. So name your class ArrayDirectory, not arrayDirectory.

public class ArrayDirectory implements Directory 
{
    public void insertEntry(Entry entry, String surname) 
    {
        System.out.println( "Doing insertEntry work." ) ;
        …
    }
}

Polymorphism

Now use that class, by instantiating an object via new. Refer to that object as the interface rather than the concrete class, if you will be calling only methods defined on the interface.

Directory directory = new ArrayDirectory() ; 

This technique is known as polymorphism (“many shapes”). A Dog object might be referred to as the more general Animal. A Circle object and a Rectangle might both be referred to as a Shape. An InternationalShippingLabel and a DomesticShippingLabel might both be referred to as a ShippingLabel. The PreferredCustomer and StandardCustomer classes can both implement the Customer interface.

Dynamic dispatch

Then call the method on that object.

directory.insertEntry( … , … ) ;

Through the magic of dynamic dispatch, at runtime the JVM locates the necessary code on the ArrayDirectory class to be executed.

By the way, notice the naming conventions at work here. Class names start with an uppercase letter, while objects (actually, reference variables) start with a lowercase letter. And, FYI, Java naming uses the full range of Unicode characters (French accents, Japanese, etc), not just English ASCII characters.

Abstract class

If the various classes have some duplicate code, make their shared interface an abstract class instead. Then you can move that duplicated code into the abstract class. This way when you later are doing reviews or doing maintenance work, you have only only place to find, study, and fix that code.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=421999&siteId=1