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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With