Lack of optional methods/operations of an implemented interface causing errors - java

** not sure if its obvious, but I am writing java
I have been trying to complete an assignment for a class of mine which requires me to implement the ListIterator<String> interface for a class. I do not wish to implement remove(), add(), or set(), which are the optional methods for the interface. But now that it is implemented, Eclipse is giving me errors saying I need to implement those methods. Does anyone know why that is or how I can solve that? Thank you in advance for your help.

They're not really optional.
You have to provide some sort of implementation, but it's common to provide an implementation that just throws an exception:
public void remove() {
throw new UnsupportedOperationException();
}
In some situations it might also be reasonable to provide a "do-nothing" implementation:
public void remove() {
// Can't remove...
}
If you do either of these, it's a good idea to document that you've done it.
If you make this an abstract class, then you don't have to implement the methods in this specific class. But at some point down the class hierarchy, you have to implement a concrete class with all the methods. Nothing actually happens until you instantiate your class in an instance, and you can't do that with an abstract class.

Interface methods are not optional, but rather insure that the class implementing the given interface implements all its methods unless it is an abstract class. When a class implements a certain interface it can be referred to as the type of the interface according to the concept of polymorphism in Java.
Example below:
public interface Herbiverous {
void eatsPlants();
}
public class Human implements Herbiverous{
public void eatsPlants() {
System.out.println("I eat plants");
}
public static void main(String[]args) {
Herbiverous h = new Human();
//in which case you can only apply the methods of the interface
h.eatsPlants();
}
}
Hope this was insightful.

Related

How the compiler will get to know which print method should be called by obj.print();?

Here is an example of interface which is showing multiple inheritance.And i want to know how can we achieve multiple inheritance by interface and why can't we use it by class?
interface Printable // interface1
{
void print();
}
interface Showable //interface2
{
void print();
}
class TestTnterface1 implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
TestTnterface1 obj = new TestTnterface1();
obj.print(); //which print method will be called now?
}
}
First question:
The implementation satisfies both contracts, so whether you cast your concrete class to Printable or Showable, it will be used just the same. You will notice that there is an "impossible" situation, like this:
public interface Printable{
String print();
}
public interface Showable{
void print();
}
public class Impl implements Printable,Showable{
/*impossible to implement because you cannot have the same method signature with two different return types*/
}
The multiple inheritance would usually imply there is something useful added by each parent. For example, if Printable would have the method #print and Showable would have the method #show, inheriting them both would add functionality to your program.
If you want to combine functionality from several concrete classes, you might want to look into composition instead of inheritance.
The answer to the second question is more tricky. You can find a longer discussion here. While it would have been possible for the creators of Java to put in such option, it would have opened the door to some pretty messed up code. Think of the example you gave: what if Printable and Showable had concrete implementations for the #print method? Which implementation should the inheriting class have chosen?
In any case the runtime will call the TestTnterface1#print() method, because it is the implementation (code that can be executed).
An interface is a contract that the class that implements must follow, and is used only at compile time. The compiler checks, if the implementor has (non abstract) methods with same name and signature.
There is only one concrete method that can be called
i.e.
class TestTnterface1 implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
Question 1: Which method is called?
There is only one method-implementation that can actually be called. So, there is no ambiguity.
Question 2: How can we achieve multiple inheritance by interface?
You already gave an example for this. The special point about this kind of inheritance is that there can't be multiple implementations (until Java 7). Java 8 in contrast allows default methods in interfaces.
Question 3: Why can't we use it by class?
It avoids inheritance of state.
https://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html gives some more information.
Since both interfaces have print() method and TestInterface1 class has its implementation, it will call its implementation.
public void print()
{
System.out.println("Hello");
}

restriction of method while implementing an interface

I have two methods in an interface:
public interface MyInterface {
public void methodOne();
public void methodTwo();
}
public class MyClass implements MyInterface{
public void methodOne(){
//implementation code
}
public void methodTwo(){
//implementation code
}
}
Can I restrict one of them while implementing the interface?
You must implement all methods of your interface, unless the class implementing the interface is abstract.
If by restrict you mean that you want to predefine one or more of the methods, then you can use an abstract class instead of the interface. Abstract methods in an abstract class are methods that must be implemented by any class that extends the abstract class. Non-abstract methods are actually implemented in the abstract class, itself.
For example,
public abstract class MyClass
{
abstract void methodOne();
void methodTwo()
{
//implementation code
}
}
public class MyOtherClass extends MyClass
{
void methodOne()
{
//implementation code
}
}
Here's a reference for Abstract Classes and Methods.
EDIT 1 (in response to comment):
I'm not really sure what you mean by a burden. All I'm saying is that if you want all methods to be implemented by the class, then use an interface.
If you only want some of the methods implemented by a class, then you can either use an abstract class instead of the interface
or
If it makes sense, have an abstract class implement the interface (partially) and then have the remainder of the methods implemented by whatever extends the abstract class.
Both approaches are reasonable. It depends on what you really need to do.
EDIT 2 (in response to additional comments):
Providing one user class with additional features seems like the perfect application for just extending the "normal user class" with a "super user" class that has the additional features. If you need an interface for the "super user" class, you can create an interface that extends the interface implemented by the "normal user" class.
No you have to implement all methods if your class implements an interface.
Unless it is abstract.
Check this discussion for more details.
You can use an abstract class; they do not need to implement all the entire interface. However, they cannot be instantiated. You must implement all methods in order to instantiate an implementation of an interface.
Except the abstract class, you are bound to implements all methods of interface.
You can not put restriction on Interface, but YES you can achieve In Abstract class and NO in concrete class.
Couple of solutions :
Either mark the class as abstract. But in that case you cannot instantiate your implementing class.
Simply add black implementation in your class.
Not sure what you mean by "restrict". You have to implement the method. However, you could simply do
public void method1(someargs) {
throw new UnsupportedOperationException();
}
as is done by many Collection implementations.

Why doesn't interfaces implement methods and override them?

I already read the post of research effort required to post a SO question. I am ashamed again to post this question to a pile of million questions. But I still don't get the idea of interfaces in java. They have unimplemented methods and then defined for every class in which they are implemented. I searched about it. Interfaces were used to support multiple inheritance in java and also to avoid (Deadly) Diamond Death of inheritance. I also came across Composition vs Inheritance and that inheritance is not for code reuse and its for polymorphism. So when I have a common code as a class to extend it will not be supported due to multiple inheritance which gives the option to use Interfaces(Correct me if I am wrong). I also came across that its not possible in most cases to define a generic implementation. So what is the problem in having a common definition (not a perfect generic implementation) of the interface method and then Override it wherever necessary and why doesn't java support it. Eg. When I have 100 classes that implements an interface 70 of them have a common implementation while others have different implementation. Why do I have to define the common method in interface over 70 classes and why can't I define them in Interface and then override them in other 30 classes which saves me from using same code in 70 classes. Is my understanding of interfaces wrong?
First, an interface in Java (as of Java 7) has no code. It's a mere definition, a contract a class must fulfill.
So what is the problem in having a common definition (not a perfect
generic implementation) of the interface method and then Override it
wherever necessary and why doesn't java support it
Yes you can do that in Java, just not with interfaces only. Let's suppose I want from this Example interface to have a default implementation for method1 but leave method2 unimplemented:
interface Example {
public void method1();
public String method2(final int parameter);
}
abstract class AbstractExampleImpl implements Example {
#Override
public void method1() {
// Implement
}
}
Now classes that want to use this method1 default implementation can just extend AbstractExampleImpl. This is more flexible than implementing code in the interface because if you do so, then all classes are bound to that implementation which you might not want. This is the advantage of interfaces: being able to reference a certain behavior (contract) without having to know how the class actually implements this, for example:
List<String> aList = MyListFactory.getNewList();
MyListFactory.getNewList() can return any object implementing List, our code manipulating aList doesn't care at all because it's based on the interface.
What if the class that uses interface already is a Sub-class. Then we
can't use Abstract class as multiple inheritance is not supported
I guess you mean this situation:
class AnotherClass extends AnotherBaseClass
and you want to extend AbstractExampleImpl as well. Yes, in this case, it's not possible to make AnotherClass extend AbstractExampleImpl, but you can write a wrapped inner-class that does this, for example:
class AnotherClass extends AnotherBaseClass implements Example {
private class InnerExampleImpl extends AbstractExampleImpl {
// Here you have AbstractExampleImpl's implementation of method1
}
}
Then you can just internally make all Example methods being actually implemented by InnerExampleImpl by calling its methods.
Is it necessary to have the interface in AnotherClass?
I guess you mean AnotherClass implements Example. Well, this is what you wanted: have AnotherClass implement Example with some default implementation as well as extend another class, or I understood you wrong. Since you cannot extend more than one class, you have to implement the interface so you can do
final Example anotherClass = new AnotherClass();
Otherwise this will not be possible.
Also for every class that implements an interface do I have to design
an inner class?
No, it doesn't have to be an inner class, that was just an example. If you want multiple other classes have this default Example implementation, you can just write a separate class and wrap it inside all the classes you want.
class DefaultExampleImpl implements Example {
// Implements the methods
}
class YourClass extends YetAnotherClass implements Example {
private Example example = new DefaultClassImpl();
#Override
public void method1() {
this.example.method1();
}
#Override
public String method2(final int parameter) {
return this.example.method2(parameter);
}
}
You can create an abstract class to implement that interface, and make your those classes inherit that abstract class, that should be what you want.
A non abstract class that implements and interface needs to implement all the methods from the interface. A abstract class doesn't have to implement all the methods but cannot initiated. If you create abstract class in your example that implements all the interface methods except one. The classes that extend from these abstract class just have to implement the one not already implemented method.
The Java interfaces could have been called contracts instead to better convey their intent. The declarer promise to provide some functionality, and the using code is guaranteed that the object provides that functionality.
This is a powerful concept and is decoupled from how that functionality is provided where Java is a bit limited and you are not the first to notice that. I have personally found that it is hard to provide "perfect" implementations which just need a subclass or two to be usable in a given situation. Swing uses adapters to provide empty implementations which can then be overrides as needed and that may be the technique you are looking for.
The idea of the interface is to create a series of methods that are abstract enough to be used by different classes that implement them. The concept is based on the DRY principle (Don't repeat yourself) the interface allows you to have methods like run() that are abstract enough to be usuable for a game loop, a players ability to run,
You should understand the funda of interface first. Which is
It is use to provide tight coupling means tight encapsulation
It helps us to hide our code from the external environment i.e. from other class
Interface should have only definition and data which is constant
It provide facility to class open for extension. Hence it cannot be replace by the any other class in java otherwise that class will become close for extension. which means class will not be able to extend any other class.
I think you are struggling with the concept of Object Oriented Design more than anything. In your example above where you state you have 100 classes and 70 of them have the same method implementation (which I would be stunned by). So given an interface like this:
public interface Printable
{
void print();
}
and two classes that have the "same" implementation of print
public class First implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
public class Second implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
you would instead want to do this:
public abstract class DefaultPrinter implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
now for First and Second
public class First extends DefaultPrinter
{
}
public class Second extends DefaultPrinter
{
}
Now both of these are still Printable . Now this is where it gets very important to understand how to properly design object hierarchies. If something IS NOT a DefaultPrinter YOU CANNOT AND SHOULD NOT make the new class extend DefaultPrinter

What's the right way to design my interface when I have operations that aren't supported by all implementers?

I have an Interface and two Classes which are implementing the Interface.
public interface MyInterface {
public void firstMethod();
public int secondMethod();
}
public class MyClass1 implements MyInterface {
public void firstMethod() {}
}
public class MyClass2 implements MyInterface {
public void firstMethod() {}
public int secondMethod() {}
}
The class MyClass1 is telling me to Add unimplemented methods, because the secondMethod is not implemented, OK I will do that. But the problem is that I don't need this method in MyClass1.
In your opinion what is the best thing to do?
Add the unimplemented method with something like return 0
There is another way to fix this if I don't want to implement it.
You should do one of the following:
Break up the interface into smaller pieces and compose as needed. This is the preferred approach, especially if you control MyInterface.
Return the most sensible default value that you can.
Throw an UnsupportedOperationException.
Here's a more illustrative example. Let's say your interface looks like this:
public interface Driveable {
public Position accelerate(Vector v, Time t);
public String getVehicleIdentificationNumber();
}
If your MyClass1 is actually a Boat and doesn't have a vehicle identification number, then it doesn't make sense for you to implement this. In fact, it's actually wrong. Other clients expect you to have this value, but you can't give it to them.
It would be better to chunk and compose the interfaces into smaller pieces, using the right slice as necessary. For example, you might instead write this:
public interface Driveable {
public Position accelerate(Vector v, Time t);
}
public interface Vehicle extends Driveable {
public String getVehicleIdentificationNumber();
}
public class Boat implements Driveable { ... }
public class Car implements Vehicle { ... }
This is the best approach since it segments the responsibilities exactly as needed across the interfaces.
If it really was important in your domain for all Driveables to have a vehicle identification number, and this is just a special case where the vehicle identification number is unknown or not available, then you can provide a default implementation:
public String getVehicleIdentificationNumber() {
return "";
}
If it would be wrong in your domain to return a vehicle identification number at all, then you should throw an exception:
public String getVehicleIdentificationNumber() {
throw new UnsupportedOperationException("vehicle identification
number not supported on boats");
}
If you still need it in the interface and it never should be called (in that implementation) I would implement make it throw an UnsupportedOperationException:
public int secondMethod() {
throw new UnsupportedOperationException("Should not be called!");
}
If there are irrelevant methods for you:
maybe you shouldn't use this interface, consider changing the design.
Add stub methods (as you did).
This depends on the requirement.
1. Interface pattern is useful when every other class implementing the interface has almost same behavior, that explains why all the method implementation is mandatory.
If you feel some class might need some methods and others not, probably you can got for abstract Class model, where you can extend and give the implementation which your class needs.
basically you have to take the call what solves your purpose to a greater extent.
for Ex: if 9 out of 10 methods you are implementing , then probably better idea is to just implement with return 0.
To achieve this, you will have to use an abstract parent class, instead of an interface (which might not be what you want).
Usually in these cases you create a base class that provides empty implementations of all interface methods, and extend from it. For example take a look at MouseAdapter
no there is no way, because you implement the Interface(with all methods inside). It wont be valid to implement just one method. This will break polimorphism
You are making a class that promises to any caller that it will do all the things that MyInterface offers.
Something is fundamentally wrong with the design if you cannot honour this commitment.
Put yourself in the position of the caller: what are they going to do with answer from secondMethod() ? Most likely it there's a sensible value such as 0 or 1 that you can return.
The important thing is that you do not surprise your caller, so I'm opposed to throwing a NotImplementedException.

Confusion in regarding implementing interface methods

HI
I have a question If interface has got four methods,and I like to implement only two methods, how this could be achieved?
Can any explain is that possible or should I go for implementing all the methods.
You can't "partially" implement an interface without declaring the implementing class abstract, thereby requiring that some subclass provide the remaining implementation. The reason for this is that an interface is a contract, and implementing it declares "I provide the behavior specified by the interface". Some other code is going to use your class via the declared interface and will expect the methods to be there.
If you know the use case does not use the other two methods you can implement them by throwing OperationNotSupported. Whether this is valid or not very much depends on the interface and the user. If the interface can legitimately be partially implemented this way it would be a code smell that the interface is poorly designed and perhaps should have been two interfaces.
You may also be able "implement" the interface by doing nothing, though this is usually only proper for "listener" or "callback" implementations.
In short, it all depends.
If you control the design of the interface, simply split it in two. One interface specifies the two only some implementations implement, and one interface specifies the other two (or inherits the first two and adds more, your choice)
You can make the implementing class abstract and implement two of the 4 methods from the interface.
I think #sateesh 's answer is the one closer to solving your problem. Let me elaborate on it. First of all, it is imperative that any class implementing an interface should provide definitions for all of its methods. But in some cases the user may find no use for a majority of the methods in the interface save for one or two. Consider the following interface having 6 abstract methods:
public interface HugeInterface {
void a();
void b();
void c();
void d();
void e();
void f();
}
Suppose your code finds use for the method 'c()' only and you wish to provide implementation details for only the method 'c()'. You can create a new class HugeInterfaceAdapter in a separate file which implements all the methods of the interface HugeInterface like shown below:
public class HugeInterfaceAdapter implements HugeInterface {
public void a() {}
public void b() {}
public void c() {}
public void d() {}
public void e() {}
public void f() {}
}
Note that you need not provide any actual implementation code for any of the methods. Now comes the interesting part. Yes, your class in which the need to implement a huge interface arose in the first place.
public class MyClass {
HugeInterfaceAdapter mySmallInterface = new HugeInterfaceAdapter() {
#Override
public void c() {
//Your class-specific interface implementation code here.
}
};
}
Now you can use the reference variable mySmallInterface in all the places where a HugeInterface is expected. This may seem a little hackish but I may say that it is endorsed officially by Java and classes like MouseAdapter bears testimony to this fact.
It's not possible.
You can implement all four methods, but the two you don't need should throw an UnsupportedOperationException.
If you want a concrete class which is implementing this interface, then it is not possible to have unimplemented methods, but if you make have abstract class implementing this interface then you can leave any number of methods as you want to be unimplemented.
As other answers mention you cannot have a concrete class implementing only some of the methods of the interface it implements. If you have no control over the interface your class is extending, you can think of having Adapter classes.
The abstract Adapter class can provide dummy implementation for the methods of an interface and the client classes can
extend the Adapter class. (Of course the disadvantage is that you cannot extend more than one class)
This is common practice with GUI programming (using Swing) where the event listener class
might not be interested in implementing all methods specified by the EventListener interface. For example
take a look at the java.awt.event.MouseListener interface and and the corresponding adapter class java.awt.event.MouseAdapter.

Categories