This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is an interface in Java?
Im confused by this term. I search google and this is what I found.
An interface is the place where two different things meet and interact. This term often comes up with regard to computers. Data processing takes place inside the computer, and thoughts take place inside the user of the computer, and they meet at an interface, which is a keyborad and a monitor screen (and usually speakers as well). [DATA -> INTERFACE <- USER]
But in this site I found this.
Java contains many libraries in those packages (Swing, etc.), and the API is the interface by which we request services (perform actions, etc.).[PACKAGES->API<-PROGRAMMER]
But in java we use it like this...
public interface A
public class B implements A
We use it to implement methods from A. Interface here is not a connection between B and methods().
The everyday definition of "interface" seems far removed from the technical meaning of interface in Java, but the two definitions are easily related. In Java, an interface is the specification of the place where an object and other code interact. As with the use of "interface" more generally, a Java object can be treated as having more than one interface.
The critical difference between a Java interface and a Java class is that an interface is purely a specification, whereas a class is a specification plus an implementation of one side of the interface (the object side). (There's an exception: if a class is declared abstract, methods can also be declared abstract, in which case their implementation is defined by subclasses.) A Java class can be declared to implement one or more interfaces, which means that the class (if it is not abstract) must include an implementation for each method specified in each interface.
Related
This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 3 years ago.
So, according to GeeksForGeeks, an interface may have fields and method signatures, but those methods cannot be defined.
A class that implements an interface must then define the body of every method in the interface it implements.
If this is the case, what is the point of the method signatures in the interface? Why not allow oneself wiggle room rather than restricting yourself to have to define methods that you may or may not want to use?
Well, there are two points in that.
First, Java supports an implementation in interfaces. You need to use the default keyword, which is in Java since Java 9 (I am not quite sure about the version number). But, why would you do that?
Interfaces share a common interface for several classes and can therefor be used as data types. You can for example write a method, which needs a parameter of an interface type. Within the method you can then call all the parameters methods, where you know their signature, based on the interface.
The point here is, that interfaces describe common behavior. That is, what interfaces are for!
The difference between (abstract) classes and interfaces is: in (abstract) classes, you define, what you have and what it will look like. Inheritance in this case then is a relation of extension (or spezialization), so you describe it in form of the child IS a parent, but it may have something more. But the IS relation is the basic point.
Interfaces describe the behavior, so a class that implements a interface acts like that interface. LinkedList and ArrayList are quite good examples. Internally they look quite different, but they both store many elements (as hash lists do too). Both classes implement the List interface, because you can both treat them as lists: you can for example iterate over them, which is not the case in hash maps.
Thus, if you want to share common structure and content, use inheritance and maybe abstract classes to group them. If you want to share common behavior, use interfaces, because it doesn't matter, how they look inside, but what you can do with them. So you group it by action.
That's not always true. You can provide a default implementation in the interface:
interface SomeInterface {
default int combine(int a, int b) { return a + b; }
}
Now the method implementing SomeInterface can override combine method, but it doesn't have to. In that case it falls back to the default implementation.
Defining methods in the interface allows you to get all benefits of polymorphism. For example, if you have a List, you don't know what exact implementation of List was used to create it - whether it's ArrayList or LinkedList or something else, but you know that you can, for example, add elements in it and get elements from it, because methods add and get are defined in the List interface.
I am working in java from some time. I know their are some thing knows as interface in java. While reading about them I come to know their is marker interface. Recently when i started reading about java 8 I come to know about an other interface Functional Interface.
I am just wondering what are the different kind of Interfaces available in java?
The Java language specification doesn't itself define the term marker interface and the term has been coined by authors, developers and designers. One common question asked is if we can create a marker interface or not and the answer is yes because of following reason:
We can't create marker interface similar to Serializable or Cloneable but we can simulate the functionality by writing extra code around the custom marker interface.
An empty interface is known as tag or marker interface. For example Serializable, EventListener, Remote(java.rmi.Remote) are tag interfaces. These interfaces do not have any field and methods in it.
Read more here: http://beginnersbook.com/2016/03/tag-or-marker-interfaces-in-java/
Functional Interface is the new addition in Java 8, An interface with exactly one abstract method is called Functional Interface. Read more here.
There are no other types of Interfaces in Java.
There's no special meaning for each.
Marker interface is kind of "design pattern", you attach a label/tag to a set of objects in order to indicates that they have something in common, they're OK for some kind of process or operations. Serializable is a typical example, it marks objects that they can be serialized/deserialized.
On the other hand for FunctionalInterface, it's just an interface with restriction that can only have one abstract method, and thus represents a single function contract. Java 8 add lambda expression for functional programming, for FP we need to pass function back and forth so often. Say we have an interface like:
public interface StringTrasformer {
String transform(Object obj);
}
Traditionally we can only create instance of asynchronous class like:
someObj.doTransform(new StringTransformer() {
#Override
public String transform(Object object) {
return "result";
}
});
But there's only one method to be implemented, so it's no need to make code so verbose, with lambda expression it could be as short as:
abc.doTransform(object -> "result");
Annotation FunctionalInterface is used for compiler to check whether the interface you have annotated is a valid one. Even functional interface is for lambda expressions, method referencesand constructor references, but nothing prevents you to use it the traditional way. Because essentially it is just an normal interface.
I've been trying to learn some basic object oriented programming in Java. I was curious to know what the origin of the word interface is , if there is any documented description. Also I was trying to make sense of what it means by thinking of a generic concept as
A point where two systems, subjects, organizations, etc. meet and interact
I got this definition from google search. What are the two systems/entities that are interfacing? Or maybe my analogy used is inappropriate?. So far I think of it as a skeleton to define methods and property outlines.
Software interfaces are one-way (though there are ways to pass the calling object as a reference to the callee), unlike Electrical connectors that interface both ways directly.
If you accept that difference in definition then the object 'implementing' the interface, is the object to be interfaced with. it allows other objects to connect to it using a well defined set of methods.
To compare it further to electronics, if 3 different types of devices all support audio-jacks, then all 3 devices essentially state: you can listen to me, I play audio. They could be very different devices (mp3 player, sonar, geiger counter) but they all clearly state: if you plug in a headphone, you can get sound out of me.
This is what an interface does in software. it states: I provide feature X, no matter what actual component I am.
so anything that implements the Map interface, can have .get(...) and .values() and .keySet() called on it. Anything that implements an AudioStream interface will yield an audiostream when called.
The object interfacing with the object supplying the interface can interact with this object in a predefined and well documented way. Ofcourse, how the object providing the interface actually makes it work can be completely different.
An interface defines the common interface (hence the name :) multiple objects (of potentially different types) have in terms of method signatures. This is for consumption by other objects.
The JLS Chapter 9 states:
An interface declaration introduces a new reference type whose members
are classes, interfaces, constants, and methods. This type has no
instance variables, and typically declares one or more abstract
methods; otherwise unrelated classes can implement the interface by
providing implementations for its abstract methods. Interfaces may not
be directly instantiated.
So this is more of a definition in terms of behavior than etymology.
The interface links your code (i.e. the class that implements your interface), and outside code. The outside code has access to your interface, but need not know your implementation.
The "two systems" (you asked for) are then the code implementing an interface and the code referencing it.
This question already has answers here:
Interface naming in Java [closed]
(11 answers)
Closed 9 years ago.
what is the convention to name interface and its implementation class in java?
Interface : ISomeService
Impl : SomeService
or
Interface : SomeService
Impl : SomeServiceImpl
Thanks!
Name your Interface what it is. Truck. Not ITruck because it isn't an ITruck it is a Truck. An Interface in Java is a Type. Then you have DumpTruck, TransferTruck, WreckerTruck, CementTruck, etc. When you are using the Interface Truck in place of a sub-class you just cast it to Truck. As in List<Truck>. Putting I in front is just crappy hungarian style notation tautology that adds nothing but more stuff to type to your code.
All modern Java IDE's mark Interfaces and Implementations and what not without this silly notation. Don't call it TruckClass that is tautology just as bad as the IInterface tautology.
If it is an implementation it is a class. The only real exception to this rule, and there are always exceptions is AbstractTruck. Since only the sub-classes will every see this and you should never cast to an Abstract class it does add some information that the class is abstract and to how it should be used. You could still come up with a better name than AbstractTruck and use BaseTruck instead. But since Abstract classes should never be part of any public facing interface it is an acceptable exception to the rule.
And the Impl suffix is just more noise as well. More tautology. Anything that isn't an interface is an implementation, even abstract classes which are partial implementations. Are you going to put that silly Impl suffix on every name of every Class?
The Interface is a contract on what the public methods and properties have to support, it is also Type information as well. Everything that implements Truck is a Type of Truck.
Look to the Java standard library itself. Do you see IList, ArrayListImpl, LinkedListImpl? No you see. List and ArrayList and LinkedList. Here is a nice article about this exact question. Any of these silly prefix/suffix naming conventions all violate the DRY principal as well.
Also if you find yourself adding DTO, JDO, BEAN or other silly repetitive suffixes to objects then they probably belong in a package instead of all those suffixes. Properly packaged namespaces are self documenting and reduce all the useless redundant information in these really poorly conceived proprietary naming schemes that most places don't even adhere to in a consistent manner. If all you can come up with to make your Class name unique is suffixing it with Impl, then you need to rethink having an Interface at all. So when you have an situation where you have an Interface and a single Implementation that is not uniquely specialized from the Interface you probably don't need the Interface.
This question already has answers here:
Why would a static nested interface be used in Java?
(11 answers)
Closed 8 years ago.
When I read about nesting an interface inside of a class, the intention appears to be to encapsulate the abstract behavior of the interface through composition. However, to me it makes more sense to create the interface outside the class, then use a getter/setter and return an instance of the interface type. There must be a benefit that I'm not seeing. Is this simply a matter of "choice".
If the interface strongly related with some class, it might be reasonable to nest it within the class. For example: SurfaceHolder.Callback which allows a client to receive information about changes to the surface in Android. The Callback interface is nested within the SurfaceHolder, and it is easier to access and find it within that context.
However, for generic interfaces such as Runnable which is implemented by a class whose instances to be executed by a thread, it is completely outside of a class (in the java.lang package for this example). This make more sense because, this interface could be used by any class, not necessarily within a specific context).
It is not a matter of choice if we talk about highly complex, scalable and re-usable systems. There are so named S.O.L.I.D. design principles (dependency injection and inversion of control if we talk specifically) which suppose the use of interfaces. The reasons to use them are:
1) the decoupling of the models inside your code. If you create the objects inside a class when your classes cannot be used in other projects as they are tightly coupled
2) possibility of creating mocks for right unit tests. You can test concrete layers, in your case by testing the highest level you invoke all the methods of the lower levels.
3) Interfaces can be combined and used throughout the whole system in many places so a lot of other classes can use the mailer server, for example