I have a class MyDoublyIterator<E> that implements the Iterator<E> interface. Also, it has a couple other methods not part of the interface (for example public void boolean hasPrev()). When I try to call that method in my main class my IDE can't resolve that method.
Here's the code I'm using to call it
Iterator<String> di = new MyDoublyIterator<String>();
di.hasPrev();
So I guess my question why can't it find that method. Do I have to build an abstract class that implements the interface and extend it?
The Problem is that the di-variable is of the type Iterator. So it could contain any implementation of this interface. And therefore the IDE cannot be sure that it contains an instance of MyDoublyIterator. So to make it work like you requested, you have to change the type of the variable to MyDoublyIterator.
It is better to first extend the original interface Iterator<E> with your own interface eg: DoubleIterator<E> with additional methods like hasPrev() and then implement the newly created interface DoubleIterator<E> in your class MyDoublyIterator<E>.
Otherwise you can instantiate your class like this:
MyDoublyIterator<String> di = new MyDoublyIterator<String>();
di.hasPrev();
Then compiler won't complain since you are creating a type of MyDoublyIterator<E>.
When compiler sees di.hasPrev(); It only knows that di is Iterator<String> and has no clue that it's your own type. So it is not aware of your custom methods.
Iterator<String> di = new MyDoublyIterator<String>();
di.hasPrev();
It won't help you. Compiler needs a way to know that your own interface has that method, and not the built-in interface Iterator interface i.e Iterator<String>. Here, you are creating a reference for the built-in Iterator interface i.e Iterator<String>.
Hence, if you have your own interface named MyDoublyIterator<E> and this interface has the method named hasPrev(); you need to do this :
MyDoublyInterface<String> di = new MyDoublyIterator<String>();
di.hasPrev();
and then it will resolve the method call, since it knows that you have created a reference of your own MyDoubleInterface<T> and it should solve the problem now. :-)
Other answers are correct, but here's another spin - create an interface that extends Iterator:
interface DoublyIterator<E> extends Iterator<E> {
boolean hasPrev();
}
class MyDoublyIterator<E> implements DoublyIterator<E> {
// ... implement methods
}
DoublyIterator<String> di = new MyDoublyIterator<String>();
di.hasPrev();
Related
When I extend a class, say class A in class B, i'm implementing all interfaces that class A implements.
In the following,
interface INTF { ... }
class A implements INTF { ... }
class B extends A { .... }
class B, being a descendant of class A, is implementing INTF.
So, what's my gain in declaring class B as
class B extends A implements INTF { .... }
?
//===========================
EDIT:
Java APIs are doing this. Eg.:
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> { ...
what for ?
TIA
There is no difference if your sub class restates that it implements an interface.But there is a huge gain when it comes to Reflection API.I have personally faced it..
When you call B.class.getInterfaces() ,it returns a Class[] containing only those interfaces explicitly declared by the class and not its superclasses,although in reality it is implementing interfaces which are implemented by its superclasses.
To solve it,you need to recursively call the super class and get all the interfaces implemented.Declaring an interface explicitly in your sub class will help you in this case
You don't have to re-declare the interface again. However, there will be differences if you using Java reflections - B.class.getInterfaces().
If you don't re-declare the interface again. B.class.getInterfaces() -- return zero interface
If you re-declare the interface B.class.getInterfaces() - Return one interface
So deciding to re-declare the interface again or Not depending on how you use java reflections on it. For most case, we don't re-declare it again.
You don't have to specify the interface again. You could specify all the implemented methods again, but you don't have to do that either.
If A changes the interface it implements in future B might not need to know about it.
It makes no difference whether you specify that B implements INTF or not, since it must implement it anyway, since A is implementing it.
I'm not sure why Java APIs are doing it. I'm assuming they simply want to make it more clear to the user of LinkedHashMap that it implements Map (otherwise the user would have to look at the declaration of HashMap to find this out).
Lets say I have class like:
class A
{
}
by any means I can make the class implements an interface on the runtime?
This is what I'm trying to achieve, when some one creates object of class A, I need to intercept the calls to that object.
Very new to Java, thanks.
A class cannot be made to implement an interface at runtime. The best that can be done at runtime is creating a dynamic subclass of your class, which additionally implements an interface.
By the Liskov Substitution Principle this solution will work quite well because any code written against your type A will also work against its subtypes. Also, any code written against the interface you are implementing will also work and be able to access the behavior implemented in your class A, to the extent to which this behavior is reflected through the behavior of the interface's methods.
You can do this with Instrumentation, however I wouldn't do this unless you know Java AND Byte Code very well and there really isn't another option.
A better option is to use composition or inheritance
class A {
}
class B extend A implement I {
// B is an A and implements I
}
A a = new B();
class C implement I {
A a;
}
Either B or C implement your interface without having to change A.
You can use a Proxy object to adapt any object at run time to make it appear as if it implements an interface.
There is a nice article here that discusses a factory method for doing this to objects.
Essentially, a Proxy object can be used to wrap an object by intercepting all method calls to the object and redirecting them dynamically.
This should be solvable with an adapter. Have an other class defined that implements your interface and delegates to the real object:
class YourAdapter implements YourInterface {
private final YourClass realObject;
public YourAdapter(YourClass realObject) {
this.realObject = realObject;
}
#Override
public methodFromInterface() {
realObject.methodFromInterface();
}
// .......
}
Now, given a method that expects YourInterface and an object of type YourClass:
void someMethod(YourInterface param) {}
void test() {
YourClass object = getFromSomewhere();
someMethod( YourAdapter(object) );
}
2nd way :
Using Proxy class :
Refer this link.
Example of dynamically implement an interface using Dynamic Proxy
I have a small question on java interfaces
Is there any way to add a new method to java interface without modifying the classes that are implementing it.
condition is that I should not introduce new interface
Is there any way to add a new method to java interface without modifying the classes that are implementing it.
No.
condition is that I should not introduce new interface
If the condition also includes not modifying the many classes that directly implement the interface, you have been given an impossible task.
This is the reason why interfaces are often accompanied by abstract Adapter classes, that implement all the methods in a do-nothing way. Implementation classes then extend the adapter rather than implementing the interface, so that if you need to add an interface you only need to modify the interface and the adapter.
What you are trying to do is fundamentally impossible. Unless (as was just pointed out in the comments) you use Java 8.
Java 8 has introduced a concept of default or defender methods that allow you to add a method to an interface and provide a default implementation of that method within the interface.
http://zeroturnaround.com/rebellabs/java-8-explained-default-methods/
The rest of the answer applies to any version of Java before 8:
An interface describes the methods in a class. If you add a new method to an interface then all classes that implement the interface must implement the method. Unless by some stroke of luck the method you are adding already exists in every single implementing class this is just impossible without either adding a new interface or changing the classes.
If your interface were an Abstract Class then you could add a stub method that does nothing and allow that to be overridden but interfaces have no concept of optional methods.
By using abstract class we can solve this problem.
interface A{
void a();
void b();
}
Class a implement A
Class b implement A ...
if any new method arrive to create an abstract class and add that method into it
abstract class adapter {
abstract void c();
}
now extend this adapter class for necessary classes..
Can Someone Explain how the methods of interface used in classes?
Note: My Doubt is "Methods are already defined in Class then why we should implement it ? "
For Example :
interface printable{
void print();
}
class A implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A obj = new A();
obj.print();
}
}
why print() is declared in interface??
You define a method by giving its implementation. They are the same thing, so you are right that once you define a method, you don't also need to implement it.
An interface declares that anything implementing this interface will defined those methods. This is part of the contract for interfaces. This allows you to call any method of an interface knowing than any concrete implementation will have such a method.
BTW In Java 8, it will support virtual extensions which means an interface can give a default implementation. This has to be defined in terms of other methods provided by the interface.
An Interface is a contract that all classes that implement it, should have a definition for the methods specified in the interface. An interface does not define the method body as such.
An interface defines a set of method which must be implemented. It says nothing on how they are implemented. This is where the class definition comes in, since it defines how these methods are implemented.
Thus, when you call a class which implements a particular interface, then you know, for sure, that you will find whatever set of methods the interface defines.
Interfaces are usually handy when you need to expose some endpoints to your application, without the need to expose the logic.
EDIT: As per your example, the printable interface defines what behaviour should a class which implements it expose, in this case print.
This will allow you to do something along the lines of printable p = new A(); p.print();.
Assuming you have something which yields an object which implements the printable interface, then, whoever is calling that method will not need to bother what is the actual implementation of the print method. The interface makes sure that whatever you are returning, will contain an implementation of that method.
#NarutoUzumaki
Welcome to Stack overflow!
I agree with Chris. You can replace the doSomething method with eat() method to get a better understanding. A dog may eat something different than a cat and to a giraffe.
Its up to you how you implement the eat method, and when using it create a reference of the interface Animal and point it to the instance of Dog, Cat or Giraffe which ever eat method you want to use. This makes your class design very extensible.
Hope you get a clear idea now.
Generally Interface based Programming is recommended, Because of the following reasons
1)Interface means rule , you should follow those rules while implementing those methods in Implemented class.
2) Dependency is less between classes while instancing your implemented class then call your methods from another class or some where.
3) You can publish your interface details only no need to disclose the implemented details of your methods to out side the world.
Defining an interface is the difference between:
public void doSomething(Dog d)
{
d.doSomething();
}
public void doSomething(Cat c)
{
c.doSomething();
}
public void doSomething(Giraffe g)
{
g.doSomething();
}
and
public void doSomething(Animal a)
{
a.doSomething();
}
Why?
Well, if all the classes just implement their own methods, there's no common reference between them. However, if they all implement the method from a common interface, they can be referred to by the same reference type; in this case Animal.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Adding Extra method to interface
There is scenario where I have Interface X, which has been implemented with my thousands of classes. Now I want to add new method in that Interface X. So how to make the changes in minimal way to solve the problem of overridden of methods in all my classes
I would create an extension of your interface for only the classes that need the additional methods...
public interface BaseInterface {
public int exampleMethod();
}
public interface ExtendedInterface extends BaseInterface {
public int anotherMethod();
}
The thousands of classes already implement BaseInterface. For the classes that need the extra method, you change them to implement ExtendedInterface.
If your objects are stored in a collection such as a BaseInterface[] array, this still works because objects of type ExtendedInterface are also objects of type BaseInterface, so they can still be stored in the same common collection.
For example, this is still perfectly valid...
BaseInterface[] objects = new BaseInterface[2];
objects[0] = new ClassThatImplementsBaseInterface();
objects[1] = new ClassThatImplementsExtendedInterface();
However, if you need to access the new method of the ExtendedInterface, but the object is stored in a BaseInterface collection, you'll need to cast it into an ExtendedInterface before you can use it...
BaseInterface[] objects = new BaseInterface[1];
objects[0] = new ClassThatImplementsExtendedInterface();
if (objects[0] instanceof ExtendedInterface){
// it is an ExtendedInterface, so we can call the method after we cast it
((ExtendedInterface)objects[0]).anotherMethod();
}
else {
// it is a BaseInterface, and not an ExtendedInterface
}
This may or may not be suitable, depending on your usage.
If you really need all your thousands of objects to implement the new method, you'll have to add the method to the BaseInterface and then use a feature of your IDE or text editor to implement the method in all your classes. For example, you could open them all in a text editor and do a find-replace to find something thats common to each class, and replace it with the common code + the default code for the new method. Pretty quick and painless. I'm sure that some IDEs would probably also automatically add the method declaration to all inheriting classes, or at least have an option to do this in a right-click menu.
If the new method is a true extension of the interface, then the right thing to do is edit the interface and use your development environment's tools to find all the places where the new functionality must be implemented. Then do the work. Eclipse and Netbeans will do a fine job.
[NB I'm a bit surprised that refactoring tools don't take care of some of the manual effort, but so it is.]
If the new method won't be called most of the time in old code, consider the new interface to be an extension of the old one:
public interface NewInterface extends OldInterface {
void newMethod();
}
If you have needs to pass old interface objects to new interface consumers with a null version of newMethod(), you can do something like:
public class NewInterfaceWrapper<T extends OldInterface> implements NewInterface {
private T wrapped;
public NewInterfaceWrapper(T wrapped) {
this.wrapped = wrapped;
}
// Define all the old interface methods and delegate to wrapped.method
// Now provide the null implementation of new method.
void newMethod() { }
}
...
wantsNewInterface(new NewInterfaceWrapper(oldImplementer));
It's not pretty, but big systems usually grow rough edges like this as they age.
There is no easy way to do that. If you add a method to the interface all implementing classes must override it. If you change the interface to an abstract class then you have to refactor the implementing classes as well.
But you have a class hierarchy right? So you can minimize the work by implementing that method in the base classes only. But that depends on your specific requirements and details so I guess happy implementing!
And if there's no easy class hierarchy that you can use to implement new methods like that perhaps it's time you think about a major rewrite in favor of future maintenance effort reduction.