Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement only required method in interface using Java

Tags:

java

I have an interface with three methods and I have implemented the two methods in my subclass.

During this, I faced a compile time error.

How do I handle this situation?

Snippet One:

package com.college.problems;

public interface MethodDefination {

    void methodOne();
    void methodTwo();
    void methodThree();        
}

Snippet Two:

package com.college.problems;

public class MethodImplementation implements MethodDefination {          

    @Override
    public void methodTwo() {
        System.out.println("Tested");
    }

    @Override
    public void methodThree() {

        throw new UnsupportedOperationException("MethodDefination.methodThree()");
    }

    public static void main (String args[]){
        MethodImplementation m = new MethodImplementation();
        m.methodTwo();
    }
}


Note: I don't want to implement all the methods that are required by the interface.

like image 287
Ramakrishnan M Avatar asked Dec 14 '22 14:12

Ramakrishnan M


2 Answers

If you don't implement all the methods of the interface, your class must be abstract, in which case you can't create an instance of it.

In Java 8, if your interface contains default implementations for some methods, you don't have to implement them in classes that implement the interface.
But of course, you can override them into sub-classes, if you need that.

like image 140
Eran Avatar answered Apr 02 '23 04:04

Eran


The answer is simple: don't implement the interface.

If you do implement it, either your class must be abstract, or you must implement all the methods defined in the interface (unless you are already inheriting an implementation).

Why not implementing it like you did methodThree? Or do something like this:

public void methodOne(){}

Though it is better to throw an Exception, just to notify the using developer he shouldn't do this, and alert the user that something unexpected happened;

like image 21
Stultuske Avatar answered Apr 02 '23 06:04

Stultuske