tmn
tmn

Reputation: 11569

Is it possible to have a Java interface that has abstract and full methods?

If I have an interface that I want developers to implement, but I want them to only override certain methods and have non-abstract methods be left alone. Like below, I want the getX() and getY() to be overridden, but I want getXPlusY() to not be. Do I have to use an abstract class with an interface to accomplish this or something?

public interface Summifier {

    public int getX();
    public int getY();

    public int getXPlusY() { 
        return getX() + getY();
    }
}

Upvotes: 2

Views: 99

Answers (3)

Mureinik
Mureinik

Reputation: 311808

In Java 8, this can be done by default methods:

public interface Summifier {

    public int getX();
    public int getY();

    // Note the default keyword
    default public int getXPlusY() { 
        return getX() + getY();
    }
}

In older versions of Java, you'd have to have an abstract class to implement this functionality.

Upvotes: 2

Claudio
Claudio

Reputation: 1858

Yes and no. In theory an interface cannot have any implementation because it defines a contract and just that.

However in Java 8 they added default methods http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html which look a lot like what you need in here.

Upvotes: 1

Kevin Workman
Kevin Workman

Reputation: 42174

Sounds like a job for a default method from Java 8: http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

Upvotes: 1

Related Questions