I have two classes A and B which both implment the interface Z. Now, class A should for some functions of Interface Z (Z.f1, Z.f2, Z.f3, ...) only work as dispatcher to an object of class B.
public class A implements Z{
private B b; //instantiated in constructor of A
#Override
public String f1(int p)
{
return b.f1(p);
}
...
Is there a generic way to do this in Java?
If you mean that method f1() is declared in interface Z the pattern you want to implement is called wrapper or decorator.
In java you can create generic implementation using dynamic proxy introduced to java 1.4.
I don't think so. But sometimes your IDE can assist in creating all the simple methods to delegate the calls. And sometimes you can find third part classes to do this. For example, Guava (http://code.google.com/p/guava-libraries/) has a ton of ForwardingXXX classes, which, by default, delegate everything to something else. For example, ForwardingMap delegates all calls to another Map. You need to override the methods that you do NOT want to delegate.
Related
There are several classes (which I can't edit) which implement an interface, is it possible to add a method that only calls methods defined in the interface to each class that implements that interface?
(without java 8)
No, I don't believe so. Such a method would have to realized in the concrete class as a real method, but without access to the classes themselves you can't do that.
You might create subclasses of each, and all those subclasses could implement you new interface with the new method.
I'm not sure if I get you right but if classes A, B, C, ... implement an interface I and you can not edit A, B, C, ... and want to add a method you propably could just extend each class with a new subclass and each subA, subB, subC and so on could implement the new method...
If you are using Java 8 and can modify the interface, then yes:
interface Face {
Object existing();
default Object additional() {
return "Hello " + existing() + "!";
}
}
Otherwise, no, you cannot. Java does not have a feature like Javascript prototypes, C# extension methods, etc at this time.
Just write a static method that takes in the interface type and calls the methods:
interface Fooable
{
void foo();
}
public class FooableExtensions
{
public static void doSomethingToFooable( Fooable f /*, other parameters*/ )
{
f.foo();
}
}
It doesn't have the fancy syntactic-sugar that C# extension methods provide, but it should do the trick.
I don't think there is a way to do what you are asking, not without resorting to byte code manipulation anyway.
Perhaps AOP would help, you could add a point cut to the target methods of the interface.
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.
I have seen in many libraries like Spring which use a lot of interfaces with single methods in them like BeanNameAware, etc.
And the implementer class will implement many interfaces with single methods.
In what scenarios does it make sense to keep single method interfaces? Is it done to avoid making one single interface bulky for example ResultSet? Or is there some design standard which advocates the use of these type of interfaces?
With Java 8, keeping the single method interface is quite useful, since single method interfaces will allow the usage of closures and "function pointers". So, whenever your code is written against a single method interface, the client code may hand in a closure or a method (which must have a compatible signature to the method declared in the single method interface) instead of having to create an anonymous class. In contrast, if you make one interface with more than one method, the client code will not have that possibility. It must always use a class that implements all methods of the interface.
So as a common guideline, one can say: If a class that only exposes a single method to the client code might be useful to some client, then using a single method interface for that method is a good idea. A counter example to this is the Iterator interface: Here, it would not be useful having only a next() method without a hasNext() method. Since having a class that only implements one of these methods is no use, splitting this interface is not a good idea here.
Example:
interface SingleMethod{ //The single method interface
void foo(int i);
}
class X implements SingleMethod { //A class implementing it (and probably other ones)
void foo(int i){...}
}
class Y { //An unrelated class that has methods with matching signature
void bar(int i){...}
static void bar2(int i){...}
}
class Framework{ // A framework that uses the interface
//Takes a single method object and does something with it
//(probably invoking the method)
void consume(SingleMethod m){...}
}
class Client{ //Client code that uses the framework
Framework f = ...;
X x = new X();
Y y = new Y();
f.consume(x); //Fine, also in Java 7
//Java 8
//ALL these calls are only possible since SingleMethod has only ONE method!
f.consume(y::bar); //Simply hand in a method. Object y is bound implicitly
f.consume(Y::bar2); //Static methods are fine, too
f.consume(i -> { System.out.println(i); }) //lambda expression. Super concise.
// the above could even be more concise
// presenting all the beauty of the recent Java changes
f.consume(System.out::println)
//This is the only way if the interface has MORE THAN ONE method:
//Calling Y.bar2 Without that closure stuff (super verbose)
f.consume(new SingleMethod(){
#Override void foo(int i){ Y.bar2(i); }
});
}
Interfaces with only one (or few) methods is the key to the highly useful Strategy pattern, which is "some design standard which advocates the use of these type of interfaces".
Another common scenario is when you want a callback. Foo calls Bar as an asynchronous task, and when Bar is finished with something, the result is sent back to Foo using a callback -- which can be an interface containing only one method. (An example of this is the many listeners in Android, Event Listeners in Swing...)
Also, if you have two classes that are tightly coupled with one another (let's call them Foo and Bar). Foo uses nearly all of Bar's methods, but Bar only needs some a few of those from Foo. Foo can implement FooInterface which is then sent to Bar. Now the coupling is looser, because Bar only knows about the FooInterface, but does not care about the other methods the implementing class contains.
In what scenarios does it make sense to keep single method interfaces?
In such a scenarios when you need an interface with only one method.
Interfaces are used to encapsulate a common behavior of several classes. So if you have several places in your code where you need to call only limited set of class methods, it's time to introduce an interface. The number of methods depends on what exactly do you need to call. Sometimes you need one method, sometimes two or more, sometimes you don't need methods at all. What matters is that you can separate behavior from implementation.
Favor Composition over Inheritance tutorial of Head First Design Pattern book recommends this approach to add functionality dynamically to a class. Let's take below case:
public interface Quackable {
public void quack();
}
public class Quacks implements Quackable {
public void quack(){
//quack behavior
}
}
public class DontQuack implements Quackable {
public void quack(){
//dont quack
}
}
public class QuackableDuck{
Quackable quack; //add behavior dynamicall
}
So QuackableDuck class can add feature dynamically.
quack = new Quacks();
//or
quack = new DontQuack();
So similarly you can add multiple behavior to the class dynamically.
You create interfaces not according to the number of methods in it but to define behaviour expected by components of your systems to deliver a single responsibility to their neighbors. If you follow this simple principle/rule, you might or might not end up with single method interfaces, depending on the responsibility you are defining. I like to keep tests stupid simple and the application very flexible so I usually have many of those
To achieve multiple inheritance, we must use interfaces, but why don't interface methods have bodies and why do they have to be overridden in the derived class?
I really want a lucid answer , not involving too much computer jargon , i cant seem to understand this , i have referred various references
Because Java, in contrast to languages like C++ or Eiffel, only has multiple inheritance of types (i.e. interfaces as well as one class), not multiple inheritance of state and behaviour. The latter of which add enormous complexity (especially state).
The Java designers (and C#, for that matter) opted to not include it as it presented C++ programmers often with very hard to debug issues. You can solve pretty much most problems that require true multiple inheritance with implementing multiple interfaces, so the tradeoff was deemed worth it.
Note that multiple inheritance of behaviour (not state) might come to Java 8 (unless they postpone it again like one of the many other things) in form of virtual extension methods where an interface can declare a method that delegates to one in another class, which then exists on all types that implement that interface.
Interfaces declare WHAT services the implementing class provides, not HOW (that's the job of the implementing class). Multiple inheritance is regarded bad, as it leads to complicated code and class hierarchies.
Interfaces only have constant variables(public + static + final) and abstract methods(public & abstract). These are meant to be used by the classes which implement the interfaces.
Interfaces simply say 'Am a contract', which if you wish to use, should stick to some rules(give implementation to all abstract methods).
Multiple inheritance is omitted in Java by making sure that a class can extend only 1 class, in order to avoid the diamond problem. You can anyways have multiple inheritance of types in Java by using interfaces.
A Java interface contains a list of methods that must be implemented by the class that implements the interface. Thus, the methods have no body: the body of each method is in the implementing class(es).
Simple Answer:
An interface provides a standard for implementation.
Explanation:
In Java an interface is similar to an abstract class in that its members are not implemented. For example,
public interface Comparable
{ boolean less(Object m);
boolean greater(Object m);
boolean lessEqual(Object m);
boolean greaterEqual(Object m);
}
An interface provides a standard for implementation.
Benefit of using interfaces is that they simulate multiple inheritance. All classes in Java must have exactly one base class, the only exception being java.lang.Object (the root class of the Java type system); multiple inheritance of classes is not allowed in java.
All instance methods are implicitly public and abstract. You can mark them as such, but are discouraged from doing so as the marking is considered obsolete practice. The interfaces themselves need not be public and several interfaces in the standard libraries are not public and thus used only internally.
An interface creates a protocol that classes may implement. Note that one can extend an interface (to get a new interface) just as you can extend a class. One can actually extend several interfaces. Interfaces thus enjoy the benefits of multiple inheritance. (Classes do not.) There are almost no disadvantages to multiple inheritance of interface (small name conflict problems are one exception). There are large disadvantages to multiple inheritance of implementation as in C++. These include efficiency considerations as well as the semantic difficulty of determining just what code will be executed in some circumstances.
The Polynomial class that implements Comparable will need to implement all of the functions declared in the interface.
public class Polynomial implements Comparable
{ . . .
boolean less(Object m){ . . . }
boolean greater(Object m){ . . . }
boolean lessEqual(Object m){ . . . }
boolean greaterEqual(Object m){ . . . }
Polynomial multiply(Polynomial P){ . . . }
. . .
}
A class may choose to implement any number of interfaces. A class that implements an interface must provide bodies for all methods of that interface. Also, We expect that an abstract class can choose to implement part of an interface leaving the rest for non-abstract subclasses.
The usefulness of interfaces goes far beyond simply publishing protocols for other programmers. Any function can have parameters that are of interface type. Any object from a class that implements the interface may be passed as an argument.
References:
Interface
Interfaces
Interface Wiki
Interface methods has no body
like
public interface Flyable
{
public void fly();
}
because interface itself not going to do anything
interface is defines contract.
an interface, on other hand, defines what a class can do,
not what it is. So interface is about verbs usually.
So the Flyable interface is doing nothing but defines the contract that the implanted
FlyableObjects are going to fly.
like:
class Rocket implements Flyable
{
public void fly()
{
// do the stuffs.
}
}
interface
and ofcourse we can achieve multiple inheritance also only and only through interface.
if interfaces had bodies then it would have brought back the Deadly Daimond of Death problem.
Consider this example having interfaces with bodies
interface A {
void print(){ System.out.print("A") }
}
interface B {
void print(){ System.out.print("B") }
}
interface C extends A, B {
// now since A and B have bodies interfaces would have had choice to not to override the default behavior
}
public class C_Implementer implements C{
public static void main(String args[]){
C c = new C_Implementer();
c.print(); // gotcha!!!!! what should it print, A or B????
}
}
You are asking "Why does Java not support multiple inheritance of implementation?"
This is discussed in the Java Tutorials, Multiple Inheritance of State, Implementation, and Type, but I wanted to give a specific example of the problems of multiple inheritance of implementation (as well as a new language feature solution at the end).
Imagine two interfaces (in our proposed version of Java that allows interface method bodies) that define a method with the same name.
public interface FaceOne {
public void method() {
System.out.println("FaceOne Version");
}
}
public interface FaceTwo {
public void method() {
System.out.println("FaceTwo Version");
}
}
And a class implements both interfaces, but doesn't override the method.
public class Inheriter implements FaceOne, FaceTwo {
}
When I call Inheriter.method(), which works since the class inherits the method from its ancestors, the problem arises: does the output print "FaceOne Version" or "FaceTwo Version"?
In addition, if the class were to override the method, but wanted to also call its ancestor's version using super, the compiler would again have trouble choosing between a version of the method.
This is why Java does not support multiple inheritance of implementation.
As an aside, I think an elegant way to implement this into the language would be as follows:
Continue to force implementing classes to override their ancestor interface's methods. This solves the first problem of a non-overridden method.
Then, use a similar notation as that of accessing an enclosing instance for an inner class to access a specific ancestor interface with super. The Inheriter class would then have multiple options:
Do not call super.method(), but rather only use newly-defined implementation.
Use FaceOne.super.method() to make the default inherited implementation output "FaceOne Version".
Use FaceTwo.super.method() to make the default inherited implementation output "FaceTwo Version".
Use a combination of the above:
One implementation could be:
#Override
public void method() {
FaceOne.super.method();
FaceTwo.super.method();
System.out.println("Inheriter Version");
}
Outputting:
FaceOne Version
FaceTwo Version
Inheriter Version
Edit: According to this question this is apparently exactly how default implementations are structured in Java 8.
The problem I am facing is as below -
I am using a 3rd party library, say Editor, which has an interface , EditorActions, with methods -
create(), edit(), delete().
I do not want to expose, EditorActions 's methods in my implementation. So my interface will have methods like -
myCreate(), myEdit(), myDelete() which in turn should call the EditorActions methods.
EditorActions is only an interface, the implementation is internal to the library.
How do I link the 2 interfaces without implementing either of them?
thanks for all your help
You can do this by exposing the methods that you want people to use in an abstract class. And then force people to implement the specific methods that you want them to.
You can then use the methods from the EditorActions interface as well as the methods that you force you implementations to implement.
public abstract class AbstractEditorActions {
private EditorActions ea;
public AbstractEditorActions(EditorActions ea) {
this.ea = ea;
}
// In this method, you can use the methods
// from the interface and from this abstract class.
// Make the method final so people don't break
// the implementation.
public final void yourExposedMethod() {
// code
this.toImplement();
ea.doMethod();
}
protected abstract toImplement();
}
Assuming you obtain an instance of EditorActions from the library you could do this:
public class FooActions implements MyEditorActions, EditorActions{
private EditorActions internal;
public FooActions(EditorActions internal){
this.internal = internal;
}
#Override
public void create(){
internal.create();
}
#Override
public void myCreate(){
// do stuff
this.create();
}
}
What this does is wrap the instance of the library object with an object that implements the same interface as well as yours. Then, you just expose the object as whatever interface you want it to be.
EditorActions a1 = new FooActions(); // a1 only shows library methods
MyEditorActions a2 = a1; // now a2 only shows your methods
How do I link the 2 interfaces without implementing either of them?
You can't. You are trying to do automatic magic here. Don't do magic. You have to implement either one of them no matter what.
Or, you'll have to implement your own reflection plumbing (or AOP somehow) to create classes on the fly. The later is no trivial manner, and typically an overkill and a red-flag of over-engineering just to avoid implementing what amounts to be a plain-old delegate.
OTH, if you only wanted to "expose" a subset of the methods provided by a third party interface A (say, for example, only the getter methods), you could almost trivially create (by good old elbow grease or a reflection library) an interface B that only exposes that subset of methods you desire.
interface DirtyThirdPartyInterface
{
StupidCrap getSomeStupidCrap();
void setStupidCrap();
}
interface MySanitizedInterface
{
StupidCrap getSomeStupidCrap();
// the setter is not part of this interface
}
Then with, say, Spring AOP or something similar or one of the several reflection libraries out there, then you could auto-generate an implementation of MySanitizedInterface as an AOP interceptor that simply proxies the call to the getter (via reflection) to the getter in the 3rd party interface.
But again, that's a lot of crap (not to mention 3rd party library dependencies) to simply avoiding what amounts to be simple hand-coding. It is rare to find a real-world case that justifies all that plumbing malarkey. If I were to run into something like that, the first thing I would think is "red flag". YMMV of course.