Let's say I have the following ruby code :
def use_object(object)
puts object.some_method
end
and , this will work on any object that responds to some_method,right?
Assuming that the following java interface exists :
interface TestInterface {
public String some_method();
}
Am I right to presume that interfaces are java's way to achieving the same thing ( with the only difference that the parameter's type would be TestInterface ) ?
You are right except that you can not define the body of a function in Java Interfaces, only prototypes.
Interfaces are the only way to implemente a pseudo multi-derivation in Java, since normal class derivation is only simple (just one parent).
No, interfaces in are not implemented. You can have multiple implementations of it though.
An interface would look more like:
interface TestInterface {
public String some_method();
}
And it could be implemented in a class:
public class TestClass implements TestInterface {
public String some_method() {
return "test";
}
}
And maybe more classes that implement this method differently. All classes that implement an interface have to implement the methods as declared by an interface.
With interfaces you can't achive exactly the same as in your Ruby example since Java is static typed.
Java interfaces define method signatures which an implementing class must provide. The JavaDoc explains all this in great detail.
In Java interfaces can only be used to declare methods, not the define (implement) them. Only classes can implement methods. But classes can implement interfaces. So you could for instance use the Adapter pattern to realize the same thing you did in ruby.
Yes, but only if you want to abstract out "anything having a some_method()" as a separate concept. If you only have one class that has some_method(), you need not specify an interface, and the parameter of use_object() will be that class.
Note also, that in Java we use camelCase instead of underscore_separated names.
It look like you are trying to program in Ruby using Java, you want want to rethink your approach to use more the idioms of the language.
Related
I am trying different combination of inner classes.I wonder that java gives you facility to write interface inside interface.It does not give me any compile time error.
Can anybody tell me what is the use of this ?
public interface IA {
public interface IB{
}
}
This enables you to put the sub interface in a namespace that might make more sense than a different package. A good example of this from the Java API is the Map.Entry interface. An Entry only really makes sense in the context of something implements the Map interface, so it is defined as an interface inside an interface.
Note that other than with inner classes, inner interfaces are always static, as Jesse Glick mentions in his answer to a related question.
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.
I just begin to maintain a Java MVC project which use Java Guice Framework.
In almost the entire code, first developers passed as parameter an empty model interface extending another interface.
Here's the first Interface:
public interface FooModel extends ModelInterface {
}
And the other interface:
public interface ModelInterface {
public void addListener(FooListener fooListener);
void setFoo(boolean blop);
boolean isFoo();
}
That does not make any sense for me.
Is there a good reason/pattern use empty interface, in Java? Maybe for Guice?
Here is a good motivation for "marker interfaces". They are especially useful in aspect-oriented programming where they give you a point to attach to (and I guess Guice is just such a framework).
Only reason i know to use an empty interface would be as a marker interface. There are some examples like java.lang.Cloneable or Serializable.
It could be used to mark a class for a specific use.
Example: IRequiresSessionState
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
WHY an Anonymous class in Java can't implement multiple interfaces directly? Simply because of syntax or there is another reason?
Hi all I was wondering why is it that Java anonymous classes couldn't implement more than one interface?
Like what problems will we have if the Java designers allowed anonymous classes to implement more than one interface?
As such:
IMammal, I4legged anonymous_creature = new IMammal, I4legged() {
{
//..
}
};
anonymous_creature.FourLeggedStuff();
anonymous_creature.MammalStuff();
Like what problems will we have if the Java designers allowed anonymous classes to implement more than one interface?
In Javas type-system there is precisely one static type for each expression. If you had to choose one static type for anonymous_creature you wouldn't be able to make much use of the variable, which is probably why you wrote
IMammal, I4legged anonymous_creature =
^^^^^^^^^^^^^^^^^
which actually changes Javas type-system fundamentally. (Possibly it has been excluded for the same reason as multiple inheritance, namely in order to keep the language simple.)
Besides, there is a trivial workaround, and that is to introduce a auxiliary interface extending both of them:
interface FourLeggedMammal extends IMammal, I4Legged {
}
and then do
... new FourLeggedMammal() { ... }
You can via an abstract class:
public abstract class AFourLeggedMammal implements IMammal, I4legged {
}
then in your code, you can do:
AFourLeggedMammal dog = new AFourLeggedMammal() {
}
dog.FourLeggedStuff();
dog.MammalStuff();
I can't see any technical problem. But anonymous inner classes should be small. Typically implementing a single method. If you want to implement more then a single interface you are probably better of with a top level class.
Of course if you absolutely have to you can create an interface that combines all the interfaces you want to implement and then create an anonymous class for that. Of course the new interface needs a name ...
http://books.google.it/books?id=G4ridwFSpIoC&pg=PA472&lpg=PA472#v=onepage&q&f=false
Paragraph that starts with "One more thing...".
An anonymous class can only implement one interface. Why? It's simply a language design choice. Nothing would make it technically impossible.
If you want to implement two or more interfaces you will have to make it a named class or use an intermediate interface or abstract class which extends (interface) or implements (abstract class) two or more other interfaces. Also, you can only refer to it only by one interface name, not two, just like all other objects in Java.
Today I got my book "Head First Design Patterns" in the mail. Pretty interesting stuff so far, however I do have a question about it's contents.
I have no Java/C# background nor do I wish to jump into those languages right now (I'm trying to focus on C++ first). In the book is said that java does not have an implementation for interfaces... This would mean that for every change to that interface, you would have to modify all subclasses that implement the interface.
How is this done in C++? What am I missing?
What the author of the book meant, if you change the signatures of the members of the interface or add new ones, you will need to make those changes in the implementing classes as well so that they keep implementing the interface.
You can change the implementing classes whatever way you want as long you have the members of the interface implemented with exactly the same signatures (that is, with the same name, return type, and the order and type of parameters).
I have the impression that you don't quite understand how interfaces work, so I suggest reading up the C# interface specification on MSDN which is quite clear on the subject I think (and it's pretty much the same in Java except that in Java you use the "implements" keyword instead of a colon (:) to declare that a class implements a specific interface).
... if you want to change the signature of a method in an interface, a good IDE (eclipse, netbeans...) can help you with refactoring all the classes implementing this interface.
It's the same situation in C++.
C++ doesn't have an interface keyword, but a pure virtual class, with all pure virtual methods, is the same idea.
If you changed method signatures in the pure virtual class, all its subclasses must follow suit in order to compile.
The C++ equivalent of a Java interface would be a class with only pure virtual methods.
You mentioned that you've "seen plenty of these Runnable/Threadable interfaces that can be modified without touching those subclasses." It's hard to say for sure from your description, but what you might have seen before is something like this:
Runnable r = new Runnable() {
public void run() {
// do something here
}
};
This is an anonymous class implementing the Runnable interface; it is not modifying the interface in any way.
An interface defines a contract that the class implementing the interface is expected to follow. This is akin to an abstract base class - which basically delegates the implementation of the methods to the deriving class.
Yes, if you modify the interface - you would have to modify all the classes that implement that interface. My guess is that the instances of Runnable that you would have seen in Java code are anonymous classes which actually implement Runnable rather than modify the interface itself.
Runnable myOwnThread = new Runnable() {
public void run() {
// Do something here
}
};
In Java, you are not allowed to modify the interfaces (and classes) provided in the standard library. The equivalent in C++ could be the pure virtual class.
Ok I'll askt he obvious question:
If you want to do design patterns in C++ why would you read anything other than the original Gang of Four Design Patterns book?
And yes a C++ class with pure virtual methods is the equivalent to a Java or C# interface.