Implements interface java [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is an interface in Java?
I have experience with object languages and object paradigm, but I have one doubt about "implements" statement. Doubt is does it includes code (functionality)? So to be very specific Does "MyClass implements XInterface" include code from other classes that implement that interface?
Class inheriting is simple including code, in a way, I know "including" may not be right word but that is what is talking place when you use "extends". You include functionality from parent class.
So let use Runnable interface for example. It has only one run() deceleration. Which could mean nothing, just that MyClass will have implementation of run(). And that what confuses me, like implementing one line deceleration in some file will make me some good... where is the actual functionality (and code) that I will get by using "implements"? So if I use:
MyClass implements Runnable {}
Runnable obj = new (Runnable) MyClass();
obj.run();//will call run() implementation from MyClass
obj.otherFunctions();/* so this calls functions from other classes that implement interface, but I don't know what functions from other classes are implementing, or even do I need them?*/
Also do I have to have one class per thread, like MyClass extends Thread implements Runnable ?

A class Cl that implements an Interface means that all methods that are defined in the interface must be implemented in class Cl. The calling class then can call these methods, because it is known that Cl implements (fullfills) the interface.
For example see the List interface: ArrayList and LinkedList both implement List, they have the same public methods (e.g add(), get()), but are internally working different.
List list = new ArrayList();
list.add(3);
later if somebody wants ArrayList to be exchanged by another class, that also implements List, only one line has to be exchanged
List list = new LinkedList();
list.add(3);
If programming to Interfaces the code is less dependent on a specific class. this has advantages when you later want to exchange one class for e,g purpose of testing, where you could controll that class by a test case.

Related

Technical difference between abstract class and interface [duplicate]

This question already has answers here:
What is the difference between an interface and abstract class?
(38 answers)
Closed 8 years ago.
Conceptually I know the difference between abstract class and interface. But wondering about the technical difference between these two. Why Sun made this interface term even though I can have fully abstract class and make my work done.
Read here http://javarevisited.blogspot.kr/2013/05/difference-between-abstract-class-vs-interface-java-when-prefer-over-design-oops.html
Difference between abstract class and interface in Java
Abstract Class vs Interface in Java and When to use them over otherWhile deciding when to use interface and abstract class, it’s important to know difference between abstract class and interface in Java. In my opinion, following two differences between them drives decision about when to use abstract class or interface in Java.
1) Interface in Java can only contains declaration. You can not declare any concrete methods inside interface. On the other hand abstract class may contain both abstract and concrete methods, which makes abstract class an ideal place to provide common or default functionality. I suggest reading my post 10 things to know about interface in Java to know more about interfaces, particularly in Java programming language.
2) Java interface can extend multiple interface also Java class can implement multiple interfaces, Which means interface can provide more polymorphism support than abstract class . By extending abstract class, a class can only participate in one Type hierarchy but by using interface it can be part of multiple type hierarchies. E.g. a class can be Runnable and Displayable at same time. One example I can remember of this is writing GUI application in J2ME, where class extends Canvas and implements CommandListener to provide both graphic and event-handling functionality..
3) In order to implement interface in Java, until your class is abstract, you need to provide implementation of all methods, which is very painful. On the other hand abstract class may help you in this case by providing default implementation. Because of this reason, I prefer to have minimum methods in interface, starting from just one, I don't like idea of marker interface, once annotation is introduced in Java 5. If you look JDK or any framework like Spring, which I does to understand OOPS and design patter better, you will find that most of interface contains only one or two methods e.g. Runnable, Callable, ActionListener etc.
I haven't included all syntactical difference between abstract class and interface in Java here, because focus here to learn when to use abstract class and interface and choosing one over other. Nevertheless you can see difference between interface and abstract class to find all those syntactical differences.
Read more: http://javarevisited.blogspot.com/2013/05/difference-between-abstract-class-vs-interface-java-when-prefer-over-design-oops.html#ixzz31l59K92Z
you are free to choose interface or abstract class in the above scenario
but keep below things in mind
if you made a fully abstract class then
your subclass will extend one class to implement that behaviour and
its not eligible to extend any other class as multiple inheritance is not supported in java.
see without interface we cant achieve multiple inheritance.
Now if we approach interface instead of fully abstract class
then class can implement it and still eligable for extension of one more class.
so choose fully abstract class in your design if your sub classes can never need to extend any other class.
if sub classes need to extend some classes later (usually its how we need in application) then choose interface.
You write a java program with interfaces, abstract class and concrete class but do not mention any constructor, compile it and see byte codes in .class files. You would see as expected abstract class and concrete classes have default constructor added by compiler where as interfaces do not get constructor added to it by compiler. This should help you understand technical differences as I believe you know other differences.
I might receive downvotes for this answer :) . Consider this scenario.
public class TestClass{
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Fish f = new Fish();
f.walk();
}
}
abstract class Animal {
protected void walk() {
System.out.println("walking");
}
}
class Fish extends Animal {
}
O/ P : walking
Technically a fish can't walk. Still since it extends the Animal class, it "can" walk which is wrong from a design perspective(even though Fish doesn't implement walk(), it can still call it).. If Animal were to be an Interface, then Fish must implement the method walk() which it won't / shouldn't. So, you will be forced to relook at the design.
Because you can have a class implement 2 interfaces, but you can't have a class implement (or extend) 2 abstract classes.
An abstract class can have some implementation code and instance variables. An interface has only method signatures and static variable definitions, no implementation code.
Further, if you implement an interface you must include implementation code for all of the methods defined in the interface.

Add new method to an interface which is directly implemented by many classes

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..

Adding new method in Java Interface so it involves minimal changes to inheriting classes [duplicate]

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.

Why Java anonymous classes couldn't implement more than one interface? [duplicate]

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.

why we need interface instead of class and what we are achieving from interface

As we know that we can declare only the method signature and also can not create the instance of a Interface. then why we need interface. Unnecessary its loading into JVM. This is also one performance degradation. We are creating the interface and several classes implementing that interface and defining all the methods of the interface. Actually what we achieved from this interface. Could you please give me some example.
Interface is you are forcing your client to implement some specified thing, implementation will be remain to the client.Also java doesn't support multiple inheritance by extending multiple classes you can have multiple interface implemented.
For example : List declares add(..) method all the implementation of List provides it implementations.
Simpler would be.
You define an Interface Animal and a method speak() it means all Animal must will have to speak with different different implementation. Man will speak,Dog will bark,Lion will roar.
Why should we go for create class Animal extra. We can declare the speak() in every class. What is befit we will get from Animal class and implementing speak() in all the sub classes. Still I did not get this concept
Main advantage is inheritance and polymorphism [core concepts of OOP]
You are specifying Animal's behavior here also.
You can have
Animal obj = new Man();
Animal obj = getAnimalForThisCriteria(something here);//this will return some animal at runtime so you can catch instance using Animal.
You might have Three different Class Ma,Dog,Lion with same method but there is no way to tell they all are animal unless they extends or implements common class or interface, here comes the concept of structure
Having interfaces separate from classes allows for clear separation between, well, the interface of an object and its implementation. Without them you would have no standard way to indicate that some class should not contain implementation details at all.
Second, since Java does not support multiple inheritance, interfaces are a partial workaround, by allowing inheritance on the outward features of the class.
Interfaces are for when you care only about an object's capabilities, not how it achieves them.
Suppose you are writing the high level control code for a robot. You don't care about how the robot actually works, you only want to be able to tell it to go forward, backward, turn left or right, etc. Without interfaces, you would implement a abstract class called AbstractRobot that has all methods as abstract methods. At this point you have basically created an interface,but in the form of an abstract class, but one that is 'heavier' than required.
Lastly, a class can conform to multiple interfaces, but can only inherit from one class. This allows some design patterns which rely on multiple inheritance.
I'll try to explain this in simple words.
Consider your favorite Computer Game, say Counter Strike.
In this game, the players (terrorists or counter-terrorists) use weapons.
If we teach the player how to use weapon (analogous to Interface), it can use any weapon like AK47, Maverick, Shotgun, Sniper (analogous to classes which inherit Weapon interface).
The advantage of this is consider Bazooka (which implements Weapon) is developed in future versions. Then the current player will be able to use it without any modifications - as it knows how to use Weapon interface :-)
This is just a simple example. There are many other reasons for using interfaces.
An analogy for an interface is to think of a class using an interface as being like an electric wall outlet, and think of the implementation as the plug. The outlet doesn't care what's behind the plug, as long as it fits in the outlet. In psuedocode terms it could be written like this:
public interface ElectricOutlet {
public void powerUp();
}
And a class that implements ElectricOutlet might look like this:
public class Appliance implements ElectricOutlet {
//member variables
public void powerUp() {
//Draw power from the wall
}
...
}
So how do you use that interface? Like this:
//lots of other code
ElectricOutlet out = new Appliance(); //plug the appliance into the outlet
out.powerUp; //power it up!
Of course, it doesn't have to be an appliance that you plug into an outlet. It could be a TV, or a laptop, or a lawn mower, but they all behave the same way from the outlet's point of view. So how does this apply to programming? In exactly the same way:
List<String> list = new ArrayList<String>(); // create a new List of Strings
I just created a new (empty) List of Strings. If it turns out that ArrayList doesn't provide the right performance, and LinkedList works better, I can go back and change that line to this:
List<String> = new LinkedList<String>(); //should work better now
I can do this because both ArrayList and LinkedList implement the List interface, and thus they provide the same behavior (API), even though the internal implementations may be different. From the List's point of view, however, it doesn't matter what the internal workings are, just as long as the interface is there. This allows a lot of independence between classes, and allows more reuse.
Simple. I think Interfaces and Abstract classes are for the same purpose. The difference is If you extend an Abstract Class, you could not extend no other class in Java. Reason: Java does not support Multiple Inheritance. At the same time, You can implement any number of Interface for a class.
The most important use of interfaces as i see it is passing code(anonymous inner class or lambda) to a method as parameter.
Example:
Suppose we want to make a method which can return the execution time required to run a piece of code. We want to pass our code as a parameter to this method.
interface Code{
public void run();
}
long getExectutionTime(Code code){
long startTime = System.nanoTime();
code.run();
return System.nanoTime() - startTime;
}
getExecutionTime(new Code(){
public void run(){
//the code to be executed
}
});
In java 8,
getExecutionTime(()->{
//the code to be executed
});
Interface is nothing but its a guide line for the new implementation
it provides some instructions for new implementation and categorize the functionality of the object .In details like if we create an interface then we create an instruction for the implementation .

Categories