zcoon zcoon - 2 months ago 6
Java Question

Error implementing Interface Methods in Class

I'm working on a simple project using Interfaces, but I am having an issue making my class conform to the interface.

My thought process is that since Article implements IDedObject, I should be able to pass an Article as a parameter in my overridden functions within my Article Class definition. Unfortunately this throws the error "The type Article must implement the inherited abstract method IDedObject.getID()"

Interface

public interface IDedObject{
public int getID(IDedObject object);
public void printID(IDedObject object);
}


Class

public class Article implements IDedObject{
private int articleID;
private String articleName;
private String authorName;

@Override
public int getID(Article article){
return article.articleID;
}

@Override
public void printID(Article article){
System.out.println(article.articleID);
}
}


What is missing or incorrect?

Answer

Only a guess since we don't have your requirements, but I think that your interface is broken, that your methods shouldn't require parameters much less parameters of its own type. Consider changing:

public interface IDedObject{
    public int getID(IDedObject object);
    public void printID(IDedObject object);
}

to:

public interface IDedObject{
    public int getID();
    public void printID();
}    

Then the implementation would be trivial

public class Article implements IDedObject{
    private int articleID;
    private String articleName;
    private String authorName;

    // constructor and other getter and setter methods here

    @Override
    public int getID(){
        return articleID;
    }

    @Override
    public void printID(){
        System.out.println("" + articleID);
    }
}

As for your compiler error -- the signature of any overridden methods must match those of the interface methods. So for instance in your Rectangle example in your link, if you extend that class or interface, then the method parameter must take the interface parameter as declared in the interface.