Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
What's the utility of interfaces other than abstraction and providing a workaround for multiple inheritance ?
If there is an Interface I having method m1() which is implemented by class A and another class B wants to access the method m(), what is the need of interface here.
Can we simply not implement that method in class A? like -
public class A implements I {
public void m1() {
// business logic goes here
}
}
public class B {
A objectOfA = new A();
objectOfA.m1;
}
This is a basic Object Oriented Programming problem. I suggest you to read OOP. Interface help to decouple your design and implemention, make it easier to reuse code. Also recomand some materials about design patterns. Head First Design Patterns is a good start and not that hard.
Put simply, an Interface is a contract. A good example is the List Interface.ArrayList and LinkedList implement the List Interface. We know that. You also know that java.util.Collections provides methods for interfaces, like sort().
The point is, this very code can be used to sort() either the ArrayList or a LinkedList, because they implement the List interface, but you can also write your own code to implement more cooler things.This way, people can use your code without having to ask you to support their classes.
Yes we can simply implement that method in class A. But let be give a example of Interface so that you can understand your code. There is a concept of Re-usability in OOPs.
An interface defines a new secondary
datatype in Java.
An interface is a reference type only
its objects cannot be created.
An interface can inherit another interface
but cannot inherit any class.
A class cannot inherit any interface but
it (a class) can implement zero to many
interfaces.
If a class implements interfaces then
1) It has to override all the abstract
methods of all the implemented interfaces.
2) Type compatibilty gets created between
the interface and the class. It allows an
interface reference can refer to object
of implementing class.
*/
interface Iface
{
int x = 3;//final and public by default
void f();//abstract and public by default
}
interface AnotherI extends Iface
{
//more declarations possible here
}
class InterfaceDemo implements Iface
{
public void f()
{
int i;
for(i =0 ; i< x; i++)
System.out.println("Interfaces are widely used");
}
public static void main(String args[])
{
Iface ref = new InterfaceDemo();
ref.f();//allowed
//ref.newMethodsOfClass();//not allowed
}
}
A practical example
List<String> list;
list = thereIsMuchData ? new ArrayList<>() : new LinkedList<>();
public void f(List<String> strings) { ... }
List being an Interface, ArrayList and LinkedList implementing classes.
You can see the following:
The implementation is your choice, based on technical knowledge. In this java distinghuishes itself from simple languages where there is one-fit-all List.
Usage of list is not overspecific.
The method f can handle all kind of lists.
I agree with #IdleMind. Also interface force you to implement all the method(s) containing the interface. You can say it is a contract to your concrete class(s) where you have implemented it.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have two similar classes. I would like to merge it into one. Objects of these classes are used in many different places. Is it possible to do it safely in Eclipse?
If you have two classes that are similar in some ways (but possibly not in others), you could create an Interface that describes the methods that are common to both of them. Then, you would have your two classes implement that Interface. Elsewhere in your application, you could reference the Interface as the formal parameters to your methods. Here's an example (see code below).
There is no automatic way to do this in an IDE-- you've got to take the time to design your object hierarchy (the relationships between your classes, and the API that your application will use to interact with them) manually.
public Interface Automobile{
//define an interface that describes the methods common to your two classes
public void drive();
}
//this is one of your two classes
public class Sedan implements Automobile{
public void drive(){
//Sedan-specific implementation here
}
}
//here's the other one. It's similar in that it has a drive method, but different
//in that it's implementation for drive() is different, and there might be
//other stuff in this class that is different from Sedan. However, it still is-an
//Automoblie
public class RaceCar implements Automobile{
public void drive(){
//RaceCar-specific implementation here
}
}
public class YourApplication{
//some method that accepts either one of the two classes you
//described as being "similar"
public void someMethod(Automobile automobile){
//you could pass in either a Sedan or a RaceCar, and
//the corresponding drive() method would get called
automobile.drive();
}
public static void main(String args[]){
Automobile car1 = new Sedan();
Automobile car2 = new RaceCar();
someMethod(car1);
//call the same method, but with car2!
someMethod(car2);
}
}
Eclipse can't do that automatically, You will have to go to one class, press control+a then control+c then go to the other class and press control+v.
Use Refactor->Extract Interface for each class to create two new interfaces and change the sources to use them instead of the classes.
Now create a new class implementing both these interfaces and remove the old classes. This should only cause your factory methods for the interfaces to break.
Change your factory methods to return this new class and leave all the interface usages in place.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've been trying to learn Java and trying to really understand it and how it works. I was able to understood what an interface was (or so I think). I've also seen some examples with them... BUT I haven't been able to understand how some interfaces have methods that you implement, and they already come with some kind of functionality... aren't you supposed to write that functionality every time you implement that method?
To give some kind of example, there's LibGDX, a very well-known library for game developing in Java. Your application class has to implement a interface that has methods like "render()". When you write your application you put all the stuff related to rendering in the "render()" method... but how does it knows what to do with that, if it's just an interface which only defines the name and return type of render()?
Sorry for my english, and thank you.
EDIT: Thanks for your answers, yes I am kind of new in this... so well I get confused, you've been really helpful!.
Interfaces
Think of an interface as a collection of abstract methods. So this special class may be implemented inside my other classes. So that it inherits it's methods.
Think of it as a child class signing a contract with this parent class and promising that it will follow the same behavior as the interface. OTHERWISE, it'll have to declare itself as an abstract class(That's a whole other question to tackle).
In Java we are not allowed to extend multiple classes(as opposed to C#) in order to keep things simple. We are however, allowed to implement as many interfaces as we need.
To give you an example, what do Apples, Oranges, Blueberries have in common? They are all fruit, thus to 'force' them to have the same characteristics I create a Fruit interface, like so:
interface Fruit {
public void name();
public void colour();
}
And then implement them in my Apple class:
public class Apple implements Fruit{
public void name(){
System.out.println("Apple");
}
public void colour(){
System.out.println("Red");
}
}
So that Apple.java is forced to use the name() and colour() method and thus we will never come across an Apple object which doesn't have both name and colour!
Hope to have cleared it up
Also, I do recommend checking - Tutorials Point
As they post rather clear tutorials. For future reference, I highly recommend you search on StackOverflow for answers prior to posting your question as it will lead to alot of negative votes!
Interfaces can definitely be challenging concept to understand. Sometimes you need to know in advance that some method will exist on a given type. LIke in your case the LibGDX has a render method. The LibGDX at some point needs to call a render method but LibGDX doesn't know how that method is implemented, it just knows that it needs to call render. So, they say please implement this interface and tell us how to render. Then when we get around to calling the render() we will make sure that it gets called at the right time and invokes your code.
Perhaps this could be said another way. Sometimes when you use other software they do lots of work for you. At some point though you have to find a way to hook into the service that they provide. By implementing that interface you provide an implementation for the render() and they are nice enough to call it for you at the right time so that the rendering can take place.
Interfaces allow for polymorphism. Essentially, the LibGDX can call the render() on anything that implements their interface. Because you have implemented their interface their code know knows that a render() must exist on the class. The reason that this is polymorphic is because many different codebases will implement the interface and provide their own custom implementation of render and again LibGDX will happily invoke their method and run their implementation of that method.
Hope that helps!
Using your example, when your class implements an interface, the framework knows an instance of your class has a render() method, so the framework can call it when it needs to.
The framework doesn't need to know (or care) what class the instance is, and especially what super classes it may be inherited from. Nor does it care what the method does.
Further, referring to objects in the most abstract way is best practice, and in java an interface is the most abstract type (because it puts no restriction on class hierarchy) - see
Liskov substitution principle for more on this concept.
This arrangement gives great flexibility to how you may implement your code.
It doesn't. An interface is simply a contract. To Java, this means that if a concrete Object exists which implements that interface, it will have implementations of the methods defined in the contract.
A simple example should help demonstrate:
ExampleInterface.java
public interface ExampleInterface {
int operation(int a, int b);
}
ExampleAddition.java - implements the interface using addition as the operation.
public class ExampleAddition implements ExampleInterface {
#Override
public int operation(int a, int b) {
return a+b;
}
}
ExampleSubtraction.java - implements the interface using subtraction as the operation.
public class ExampleSubtraction implements ExampleInterface {
#Override
public int operation(int a, int b) {
return a-b;
}
}
ExampleMain.java - Contains anonymous inner class which uses multiplication as the operation.
public class ExampleMain {
public static void main(String[] args) {
ExampleInterface first = new ExampleAddition();
ExampleInterface second = new ExampleSubtraction();
ExampleInterface third = new ExampleInterface() {
#Override
public int operation(int a, int b) {
return a*b;
}
};
System.out.println(first.operation(10,5));
System.out.println(second.operation(10,5));
System.out.println(third.operation(10,5));
}
}
So what's the point of all this? Well the point is that all interface implementations are interchangeable, and you can use whichever you fancy. Now clearly in this example it's not particularly useful. It's more useful if you have for instance a data access object, and you want to use different technologies to access your data layer. You might want to have a hibernate implementation in production, and plain old JDBC implementation for local development, and a Mockito version for testing. This can all be done, because they share a common interface, they are effectively drop-in replacements for each other. In libGDX however I suspect there will only ever be one implementation, but it still must comply to the same contract. This let's them write a game loop that works independently of your concrete implementation.
This question already has answers here:
what is the actual use of interface in java? [duplicate]
(6 answers)
Closed 9 years ago.
I am just in little bit confusion about for what interface used in Java.
For example, I am creating an interface like,
interface Inter
{
void get();
}
And I am implementing it in a class like,
class Base implements Inter
{
void get()
{
------
}
}
Whats the difference between, if I declare a class like
class Base
{
void get()
{
------
}
}
Is there any difference in it? then why should I use interface in java. I know its a basic question. but I am in confusion. So please solve this..
An interface makes the contract between caller and called classes more explicit.
Also, it allows you to mimic multiple inheritance to a certain extent (say you
have super class A and you cannot change it, you can still implement some
interface B and pass your class to a method which accepts B as parameter
but knows nothing about your super-class A).
public interface Animal {
public void eat();
public void sleep();
}
public class Dog implements Animal{
// Now FOR A DOG TO BE AN ANIMAL, IT MUST IMPLEMENT ALL THE BEHAVIOURS(METHODS) OF ANIMAL INTERFACE. IF IT MISSES EVEN ONE BEHAVIOUR, THEN A DOG IS NOT AN ANIMAL.
public void eat()
{
}
public void sleep()
{
}
}
Why Interfaces?
An interface is a contract or a protocol, or a common understanding of what the classes can do. When a class implements a certain interface, it promises to provide implementation to all the abstract methods declared in the interface. Interface defines a set of common behaviors. The classes implement the interface agree to these behaviors and provide their own implementation to the behaviors. This allows you to program at the interface, instead of the actual implementation.
One of the main usage of interface is provide a communication contract between two objects. If you know a class implements an interface, then you know that class contains concrete implementations of the methods declared in that interface, and you are guaranteed to be able to invoke these methods safely. In other words, two objects can communicate based on the contract defined in the interface, instead of their specific implementation.
First, it can be usefull because you can't herit from multiple class.
And then it is a kind of contract also.
All classes which implements Movable will be able to move, but each one with his own way.
So when you handle a Movable, no matter his class, you know that you can use the method move().
Hope it helps.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
In all examples I have seen that interfaces are used to achieve polymorphism. Now we have the following code with abstract class
AbstractClass parent = new Child();
Here the man stated that
A common argument is that Polymorphism only applies to interfaces and
not abstract classes.
I think he meant they are usually interfaces that are used in polymorphism in Java. As I see many people found his question silly and wanted URL. This here what I found. So my question is it a good/common practice to use abstract classes in polymorphism (as in my example - because polymorphism is very wide definition) in Java?
It is good practice to use the most general parent that meets the contract; if the interface defines all of the function signatures you need then use them rather than abstract classes implementing that interface. The article Design Principles from Design Patterns by Bill Venners in discussion with Erich Gamma goes into detail.
One of their best uses is where you have a common behaviour between "childs".
Your interface
interface Drawable{
void paint();
}
An abstract class with common code
abstract class AbstractRectangularObject implements Drawable{
public void paint(){
paintVertices();
//your code to fill body
}
//Abstract method that all subclases needs to implement
protected abstract void paintVertices();
}
Your real subclasses
class Rectangle extends AbstractRectangularObject {
protected void paintVertices(){
//code to pain vertices
}
}
-
class RoundRectangle extends AbstractRectangularObject {
protected void paintVertices(){
//code to pain vertices
}
}
If You have common functinality and properties to share between child classes and at the same time the class itself is too abstract to have instance, it will be good practice to use abstract class. If no I will prefer to use interfaces.
In general, yes. It is always good practice to use the least specific type necessary. This applies in to concrete super classes, too, not just abstract classes and interfaces.
public class MyClass{} // not an interface and not abstract
public class SubClass extends MyClass{}
public class OtherClass{
public MyClass getMyClass(){
return new SubClass();
}
]
In practice, it depends on the situation. If everything is contained within the scope of say one method, it really doesn't matter.
public void doStuff(){ // void method, so never going return any details
AbstractFoo foo1= new ConcreteFoo();
// no better than
ConcreteFoo foo2 = new ConcreteFoo();
// because nothing external to this method will ever know
}
However, the reason behind having developers always use the least specific implementation (or interface) is to just make it a habit.
Answer depends on your context.
Example:
// Abstract class template
abstract class AbstractFirst {
public void doSomething(){
this.doOne();
this.doSecond();
System.out.println("");
System.out.println("Test");
}
public abstract void doOne();
public abstract void doSecond();
}
// Concrete implementation
class ConcreteFirst extends AbstractFirst {
public void doOne(){System.out.print("One"); } // must be implemented
public void doSecond(){System.out.print("Second"); } // must be implemented
public static void main(String[] args){
ConcreteFirst cf = new ConcreteFirst();
c.doSomething();
}
}
This prints
OneSecond
Test
to console. This is not possible with Interfaces. This pattern is called "Template method pattern" and is one of the GoF Patterns
As to my experience, abstract class always contains partial implementation of some interface. This is the case for EJBs, for example. Its a better design to keep API and its implementation separate, even partial. So Id recommend make an interface and an abstract class. But for references use interface rather then abstract class.
Regarding to your question there's not such opinion that say it's a bad practice to use polimorphism, it's a good practice to use it where it applies, but it depends on usecases where you define the requirements for the classes to be pure virtual aka interfaces.
Closed. This question is opinion-based. It is not currently accepting answers.
Closed 4 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Let's say I wanted to define an interface which represents a call to a remote service. Now, the call to the remote service generally returns something, but might also include input parameters. Suppose that an implementing class will typically only implement one service method. Given the above information, is the following a poor design (it doesn't quite feel right):
public interface IExecutesService<A,B>
{
public A executeService();
public A executeService(B inputParameter);
}
Now, let's say that I implement this interface with a class that executes a remote service with an input parameter:
public class ServiceA implements IExecutesService<String,String>
{
public String executeService()
{
//This service call should not be executed by this class
throw new IllegalStateException("This method should not be called for this class...blabla");
}
public String executeService(String inputParameter)
{
//execute some service
}
I have two questions regarding the above:
Is the use of a generic interface (IExecutesService<A,B>) good in the case where you want to provide subclasses which require different input parameters and return types for the interface methods?
How can I do the above better? I.e. I want to group my service executors under a common interface (IExecutesService); however, an implementing class will typically only implement one of the methods, and the use of an IllegalStateException feels really ugly. Also, the B type parameter in IExecutesService<A,B> will be redundant for an implementing class that calls a service without any input parameters. It also seems overkill creating two separate interfaces for the two different service calls.
Here's one suggestion:
public interface Service<T,U> {
T executeService(U... args);
}
public class MyService implements Service<String, Integer> {
#Override
public String executeService(Integer... args) {
// do stuff
return null;
}
}
Because of type erasure any class will only be able to implement one of these. This eliminates the redundant method at least.
It's not an unreasonable interface that you're proposing but I'm not 100% sure of what value it adds either. You might just want to use the standard Callable interface. It doesn't support arguments but that part of the interface has the least value (imho).
Here's another suggestion:
public interface Service<T> {
T execute();
}
using this simple interface you can pass arguments via constructor in the concrete service classes:
public class FooService implements Service<String> {
private final String input1;
private final int input2;
public FooService(String input1, int input2) {
this.input1 = input1;
this.input2 = input2;
}
#Override
public String execute() {
return String.format("'%s%d'", input1, input2);
}
}
I'd stay with two different interfaces.
You said that 'I want to group my service executors under a common interface... It also seems overkill creating two separate interfaces for the two different service calls... A class will only implement one of these interfaces'
It's not clear what is the reason to have a single interface then. If you want to use it as a marker, you can just exploit annotations instead.
Another point is that there is a possible case that your requirements change and method(s) with another signature appears at the interface. Of course it's possible to use Adapter pattern then but it would be rather strange to see that particular class implements interface with, say, three methods where two of them trow UnsupportedOperationException. It's possible that the forth method appears etc.
As an answer strictly in line with your question, I support cleytus's proposal.
You could also use a marker interface (with no method), say DistantCall, with several several sub-interfaces that have the precise signatures you want.
The general interface would serve to mark all of them, in case you want to write some generic code for all of them.
The number of specific interfaces can be reduced by using cleytus's generic signature.
Examples of 'reusable' interfaces:
public interface DistantCall {
}
public interface TUDistantCall<T,U> extends DistantCall {
T execute(U... us);
}
public interface UDistantCall<U> extends DistantCall {
void execute(U... us);
}
public interface TDistantCall<T> extends DistantCall {
T execute();
}
public interface TUVDistantCall<T, U, V> extends DistantCall {
T execute(U u, V... vs);
}
....
UPDATED in response to OP comment
I wasn't thinking of any instanceof in the calling. I was thinking your calling code knew what it was calling, and you just needed to assemble several distant call in a common interface for some generic code (for example, auditing all distant calls, for performance reasons).
In your question, I have seen no mention that the calling code is generic :-(
If so, I suggest you have only one interface, only one signature. Having several would only bring more complexity, for nothing.
However, you need to ask yourself some broader questions :
how you will ensure that caller and callee do communicate correctly?
That could be a follow-up on this question, or a different question...
If I understand correctly, you want to have one class implement multiple of those interfaces with different input/output parameters? This will not work in Java, because the generics are implemented via erasure.
The problem with the Java generics is that the generics are in fact nothing but compiler magic. At runtime, the classes do not keep any information about the types used for generic stuff (class type parameters, method type parameters, interface type parameters). Therefore, even though you could have overloads of specific methods, you cannot bind those to multiple interface implementations which differ in their generic type parameters only.
In general, I can see why you think that this code has a smell. However, in order to provide you with a better solution, it would be necessary to know a little more about your requirements. Why do you want to use a generic interface in the first place?