What's the purpose of empty interfaces besides readability? [duplicate] - java

I am aware of what marker interface is and when we need to use it. One question is still not clear to me. If a marker interface does not have any method or body, how does it work at runtime?

A marker interface doesn't "work" as such. As the name suggests, it just marks a class as being of a particular type. Some other code has to check for the existence of the marker and do something based on that information.
These days annotations often perform the same role that marker interfaces did previously.

The only useful thing you can do with it is
if (instance instanceof MyMarkerInterface) {
...
}

Marker interfaces can be replaced with annotations in many places, however a marker interfaces can still be used for
The compile time checks. You can have a method which must take an object of a class with a given marker interface(s) e.g.
public void myMethod(MyMarkerInterface MMI);
You cannot have this compile time check using an annotation alone.
BTW: You can have two interfaces using generics, but good examples are rare.
Support frameworks which depend on interface(s) to identify a component type. like OSGi.
EDIT: I use this for a Listener marker interface. A listener has methods methods marked with annotations but the methods can have any name or type. It adds a compiler time check to what would otherwise be a purely runtime linking.
public Component implements Listener {
#ListenerCallback
public void onEventOne(EventOne... eventOneBatch) { }
#ListenerCallback
public void onEventTwo(EventTwo eventTwo) { }
}

Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface. e.g. serializable, Clonnable and Remote Interface. They are used to indicate signal or command to the compiler Or JVM. It can also be used to classify code. You can also write your own marker interface and use them to logically divide your code. Also, you can write any pre-processing operation on those class.

A marker interface tells JVM that the class being marked by marker interface to add functionality of a marker interface . Like implementing Cloneable tells JVM that this class implements Cloneable and hence JVM will have to copy it bit-wise.

Related

Every interface with a single abstract method should be a functional interface? [duplicate]

This question already has answers here:
What are functional interfaces used for in Java 8?
(11 answers)
Closed 3 years ago.
Recently I started in a new project where all the interfaces with a single abstract method are anotated with #FunctionalInterface. Constantly I see people removing the annotation after adding another abstract method in the interface. When did I ask why? They told me that someone that isn't in the company anymore told them to do it like that. Now I'm not sure if it's a good idea to annotate interfaces that obviously will not be used with lambdas.
Now I see that a piece of useful information is that people are using the anotation even in services in services. I just seemed a code like:
#FunctionalInterface
public interface SomeService {
void doSomething();
}
I'm not sure if it's a good idea to annotate interfaces that obviously
will not be used with lambdas
It's not. At best, it's a waste of time. At worst, it's actively misleading.
The documentation says
[Use to indicate that the type] is intended to be a functional interface
If you say it will "obviously not" be used in a lambda then using a annotation that marks that you do expect that usage is a clear contradiction.
Explanation
Every interface that only offers one (abstract) method, i.e. without implementation, is a so called functional interface.
Being it explicitly or implicitly.
The annotation #FunctionalInterface is, like #Override, optional, if you want to create a functional interface.
So if you declare an interface #FunctionalInterface, but it actually has more than just one such method, the compiler helps you and prevents compilation with an error. Telling you that you violated your own intention.
If you do not have the annotation, it will compile, but it is not a functional interface anymore. This could be a bug to you, because your intention was to create a functional interface. Note that if you are actually using the interface in an environment where a functional interface is actually required, like for a lambda, it would obviously not compile anymore as soon as another method is added to the interface.
Here are some examples:
// is a functional interface
interface Foo {
void bar();
}
// is a functional interface
#FunctionalInterface
interface Foo {
void bar();
}
// is not a functional interface
interface Foo {
void bar();
void baz();
}
// does not compile
#FunctionalInterface
interface Foo {
void bar();
void baz();
}
Use
It is to make your intention clear to the compiler, other team members and your future self. That way, the compiler can help you spot bugs in case you mess up.
Another scenario might be if you are working in a team and design an interface. If you do not clearly mark this interface as functional interface, either by the annotation or with a comment/documentation, another team member might not know your intention and add more methods to it.
This is especially important if you are a library designer, i.e. writing code that is to be used by other, external, people. If you mark your interface #FunctionalInterface, it is a promise to them that you intent to keep it like that. So they can safely use it for lambdas, for example. Without fearing that their code will break as soon as you ship an update to your library.
The opposite case is true as well. If they spot an interface of yours that only has one method, but is not explicitly annotated, they will understand that this is not meant to be used as functional interface, eventhough it currently is one. Thus, they will not use it for lambdas, although they could, since you might change it in a future update.
Details
You can read about the precise definitions in JLS§9.8. Functional Interfaces:
A functional interface is an interface that has just one abstract method (aside from the methods of Object), and thus represents a single function contract. This "single" method may take the form of multiple abstract methods with override-equivalent signatures inherited from superinterfaces; in this case, the inherited methods logically represent a single method.
And JLS§9.6.4.9. #FunctionalInterface:
The annotation type FunctionalInterface is used to indicate that an interface is meant to be a functional interface (§9.8). It facilitates early detection of inappropriate method declarations appearing in or inherited by an interface that is meant to be functional.
It is a compile-time error if an interface declaration is annotated with #FunctionalInterface but is not, in fact, a functional interface.
Because some interfaces are functional incidentally, it is not necessary or desirable that all declarations of functional interfaces be annotated with #FunctionalInterface.
The last paragraph here is especially important. I.e. you might have created a functional interface incidentally and plan to add more to it later. So people should not mistake this and use it with lambdas, otherwise their code will break later, when you add more methods.
Note
As mentioned before, the #Override tag works the same, but for overriding methods. So you can also override methods without it. But if you use it and maybe made a typo, i.e. you are not actually overriding something, the compiler will help you spot this issue immediately.

Why should I use an interface when there is only one implementation class?

I'm new at programming and I'm learning Java.
I was just wondering why I should use an interface when there is only one implementation class?
You do this to prevent others from accessing your implementing type. For example, you could hide your implementing type inside a library, give the type package access, and return an instance of your interface to the users of your library:
// This is what the users of your library know about the class
// that does the work:
public interface SomeInterface {
void doSomethingUseful();
void doSomethingElse();
}
// This is the class itself, which is hidden from your clients
class MyImplementation implements SomeInterface {
private SomeDependency dependency = new SomeDependency();
public void doSomethingUseful() {
...
}
public void doSomethingElse() {
...
}
}
Your clients obtain objects like this:
public class MyFactory {
static SomeInterface make() {
// MyFactory can see MyImplementation
return new MyImplementation();
}
}
This trick becomes useful when the implementation uses lots of libraries. You efficiently decouple the interface of your library from its implementation, so that the user wouldn't have to know about the dependencies internal to your library.
One reason is to maintain the open/closed principle, which states that your code should be open for extension, but closed for modification. Although you only have one implementing class now, chance is that you will need another differing implementation class with the passing of time. If you extract the implementation into an interface beforehand, you just have to write another implementing class ie. You don't have to modify a perfectly working piece of code, eliminating the risks of introducing bugs.
You shoulnt do anything without thinking and reasoning.
There might be cases where you might want to add an interface even for a single implementation ... but IMO that's an OBSOLETE PRACTICE coming from old EJB times, that people use and enforce without the proper reasoning and reflection.
... and both Martin Fowler, Adan Bien, and others has been saying it for years.
https://martinfowler.com/bliki/InterfaceImplementationPair.html
https://www.adam-bien.com/roller/abien/entry/service_s_new_serviceimpl_why
To respect the Interface Segregation Principle.
The decision to create an interface should not be based on the number of implementing classes, but rather on the number of different ways that object is used. Each ways the object is used is represented by an interface, defined with the code that uses it. Say your object needs to be stored in memory, in collections that keep objects in order. That same object and also needs to be stored in some persistent storage.
Say you implement persistence first. What is needed by the storage system is a unique identifier for the persisted objects. You create an interface, say Storable, with a method getUniqueId. You then implement the storage.
Then, you implement the collection. You define what the collection needs from stored objects in an interface, like Comparable, with a method compareTo. You can then implement the collection with dependency on Comparable.
The class you want to define would implement both interfaces.
If the class you are defining implement a single interface, that interface would have to represent the needs of the collection and storage system. That would cause, for example:
unit tests for the collection would have to be written with objects that implement Storable, adding a level of complexity.
if the need arise later to display the object, you would have to add methods needed by the display code to the single interface, and modify the tests for collection and storage to also implement the methods needed for display.
I talk about impact on test code here. The problem is larger if other production level objects need storage and not display. The larger the project, the larger the issue created by not respecting the interface segregation principle will become.
It can give you the flexibility to add more implementations in the future without changing the client code which references the interface.
Another example of when it can be useful is to simulate multiple inheritance in Java when it is needed. For example, suppose you have an interface MyInterface and an implementation:
public interface MyInterface {
void aMethod1();
void aMethod2();
}
class MyInterfaceImpl implements MyInterface {
public void aMethod1() {...}
public void aMethod2() {...}
}
You also have an unrelated class with its own hierarchy:
public class SomeClass extends SomeOtherClass {
...
}
Now you want to make SomeClass be of type MyInterface but you also want to inherit all the code that is already existing in MyInterfaceImpl. Since you cannot extend both SomeOtherClass and MyInterfaceImpl, you can implement the interface and use delegation:
public class SomeClass extends SomeOtherClass implements MyInterface {
private MyInterface myInterface = new MyInterfaceImpl();
public void aMethod1() {
myInterface.aMethod1();
}
public void aMethod2() {
myInterface.aMethod2();
}
...
}
I see a lot of good points being made in this post. Also wanted to add my 2 cents to this collection of knowledge.
Interfaces Encourage parallel development in a team environment. There can be 2 classes A and B, with A calling B's API. There can be 2 developers simultaneously working on A and B. while B is not ready, A can totally go about it's own implementation by integrating with B's interfaces.
Interfaces serve as a good ground for establishing API Contracts between different layers of code.
It's good to have a separation of concerns with Interface handling implicit API documentation. it's super easy to refer to one and figure which APIs are accessible for the clients to call.
Lastly, it's better to practice using interfaces as a standard in a project than having to use it on a case by case bases (where you need multiple implementations). This ensures consistency in your project.
For the Art that Java Code is, interfaces make thmem even more beautiful :)
Interfaces can be implemented by multiple classes. There is no rule that only one class can implement these. Interfaces provide abstraction to the java.
http://www.tutorialspoint.com/java/java_interfaces.htm
You can get more information about interfaces from this link

Why we need default methods in Java? [duplicate]

This question already has answers here:
Purpose of Default or Defender methods in Java 8
(5 answers)
Closed 8 years ago.
I'm taking a look to Java 8 news compared to 7 and in addition to very interesting things like lambdas or the new time framework, i found that a new feature(?) was introduced: default methods.
I found the following example in this article:
public interface Math {
int add(int a, int b);
default int multiply(int a, int b) {
return a * b;
}
}
It seems very strange to me.
Above code looks like an abstract class with an implemented method. So, why to introduce default methods in an interface? What is the actual advantage of this approach?
In the same article I read this explaination:
Why would one want to add methods into Interfaces? We’ll it is because interfaces are too tightly coupled with their implementation classes. i.e. it is not possible to add a method in interface without breaking the implementor class. Once you add a method in interface, all its implemented classes must declare method body of this new method.
Well this doesn't convince me at all. IMHO I believe that when a class implements an interface obviosly must declare methods body for each method in it. This is surely a constraint, but it's also a confirm of its "nature" (if you understand what I mean...)
If you have common logic to every inheriting class you'll put it into an implementing abstract class.
So, what's the real advantage of a default method? (It looks more like a workaround than a new feature...)
UPDATE I understand that this approach is for backwards compatibility, but it still doesn't convince me so much. An interface represent a behaviour that a class MUST have. So a class implementing a certain interface has surely this behaviour. But if someone can arbitrarily change the interface, this constraint is broken. The behaviour can change anytime... Am I wrong?
This is for backwards compatibility.
If you have an interface that other people have implemented then if you add a new method to the interface all existing implementations are broken.
By adding a new method with a default implementation you remaining source-compatible with existing implementations.
For a slightly simple/contrived example that should hopefully demonstrate this let us say you created a library:
void drawSomething(Thing thing) {
}
interface Thing {
Color getColor();
Image getBackgroundImage();
}
Now you come to do a new version of your library and you want to add the concept of border colors, that's easy to add to the interface:
interface Thing {
Color getColor();
Color getBorderColor();
Image getBackgroundImage();
}
But the problem is that every single person using your library has to go back through every single Skin implementation they ever did and add this new method.
If instead you provided a default implementation to getBorderColor that just called getColor then everything "just works".
There have been a lot of methods acting on an abstract interface in the past. Before Java 8 they had to be put into an additional class pairing the interface, e.g. Collections with Collection.
This old approach was neither more convincing than default methods nor more practical. Instead of list.sort() you had to say Collections.sort(list). This also implies that you had to make a fundamental decision when creating an interface, either you require every List implementation to implement a sort method or you provide a sort method in a utility class that cannot be overridden.
With default methods you can have both, a standard implementation which the List implementations do not need to implement on its own but still can be overridden if a concrete implementation has a more efficient way to do it knowing its internals, e.g. ArrayList.sort passes its internal array directly to Arrays.sort skipping some intermediate operations.
Suppose at some point you want to add new functionality in declared interface, up to Java 7, If you will add a new method in declared an interface, you also have to define the implementation of the method in classes that are implementing that interface.
In java 8, You can add a default method containing the implementation and all the child class will inherit that method.
Edit : (After question update)
An interface represent a behaviour that a class MUST have
It still represent a behaviour that class must have, your confusion is how you are defining behaviour. All implementing class will inherit default method and are also free to write their own implementation. consider following two cases,
If implementing class does not provide own implementation and simply inherit default method. If you change behaviour of default method in interface, implementing classes will be having updated behaviour as they inherit default method so it holds An interface represent a behaviour that a class MUST have.
If implementing class provide own version of default method, and if you will change behaviour (only arguments) of default method. In this case implementing class will be having two overloaded methods, one which was earlier defined and second one is inherited default method. and if you change complete behaviour (arguments with return type also), It will create ambiguity in implementing class as you can not overload method by changing return type and Implementation will be broken. again it holds An interface represent a behaviour that a class MUST have.
Example :
Bulk data operation in collection is added in Java 8 (Reference : http://openjdk.java.net/jeps/107), to implement that forEach() method is added in Iterable interface. Adding abstract method in Iterable interface would break all the existing code because each class has to implement that method.
Solving the issue, following default forEach() method is added in Iterable interface,
interface Iterable
{
default void forEach(Consumer<? super T> action)
{
for (T t : this) action.accept(t);
}
}
Reference : Java 8 : Default method in Interface

Interface with no methods

Why do Java introduces some interface which has no methods defined in it? For example Cloneable, Serializable, Type and many more.
Second thing : In Class.class package there is one method defined registerNatives() without body and is called from static block but Class.class is not abstract but is final. Why so?
and Why Java need some method without body to be called from static block.?
Why do Java introduces some interface which has no methods defined in it?
This are called Tagged or Marker interface. These are not used for any use or operation. These methods are used to tag or marking a class. So that you can determine whether someclass is a child of those classes.
about the second question
If you look closely you can see the declaration is
private static native void registerNatives();
So registerNatives is a native methods.
So what is native methods. If you see this so question
The method is implemented in "native" code. That is, code that does
not run in the JVM. It's typically written in C or C++.
Native methods are usually used to interface with system calls or
libraries written in other programming languages.
So these methods are loaded from native codes. So you don't need to declare the body of the methods but still they are not abstract as they have their implementation from native codes.
Marker interface is used as a tag to inform a message to the java compiler so that it can add special behavior to the class implementing it. Java marker interface has no members in it.
The purpose of Marker interfaces is to force some kind of functionality in the classes by providing some functionality to a class if it implements the marker interface.
Read Java Marker Interface also see What is the use of marker interfaces in Java?
For the first one you are actually asking for a Marker Interface. Marker Interfaces are by design not supposed to add anything to behavior but support only polymorphic transformation of the object. e.g. Serializable makes an object capable of streaming across JVM boundaries. Marker interfaces follow the 'universal type substitution' philosophy.
For second one, you are actually asking for JNI. Java doesnot implement all its code in Java form. I mean in classes and code that follow Java syntax. Some time or the other you need to drill down to the native platform API to implement something for that API. e.g. sockets and TCP communication. It is this feature of Java that actually makes it platform independent. The JVM runtime is platform dependent as it uses platform based native methods and dll or .so libraries to implement and integrate with the platform. We as programmers call the high level Java SDK API calls.
One of the "clean" features of the Java programming language is that it mandates a separation between interfaces (pure behavior) and classes (state and behavior). Interfaces are used in Java to specify the behavior of derived classes.
Often you will come across interfaces in Java that have no behavior. In other words, they are just empty interface definitions. These are known as marker interfaces. Some examples of marker interfaces in the Java API include:
java.lang.Cloneable
java.io.Serializable
java.util.EventListener
Marker interfaces are also called "tag" interfaces since they tag all the derived classes into a category based on their purpose. For example, all classes that implement the Cloneable interface can be cloned (i.e., the clone() method can be called on them). The Java compiler checks to make sure that if the clone() method is called on a class and the class implements the Cloneable interface. For example, consider the following call to the clone() method on an object o:
SomeObject o = new SomeObject();
SomeObject ref = (SomeObject)(o.clone());
If the class SomeObject does not implement the interface Cloneable (and Cloneable is not implemented by any of the superclasses that SomeObject inherits from), the compiler will mark this line as an error. This is because the clone() method may only be called by objects of type "Cloneable." Hence, even though Cloneable is an empty interface, it serves an important purpose.
registerNatives()
native method are implemented in JVM itself.
What does the registerNatives() method do?
Why Java need some method without body to be called from static block.?
This is called from static block because we need to call this method when classes are loaded and not when it's instance is created.

interface is implemented by thousands of classes so if changes occurs in interface then how to reduce it

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
If the method implementation is common to all classes, maybe an abstract class is better then interface for it.
If it isn't - you are going to write these methods anyway.
(*)It was initially a comment, but I was requested to put it as an answer.
If your new method doesn't make sense for all implementations of that interface, don't add it there - make a new interface that extends your original one
If there should be a default implementation for all your thousand classes - change your interface to an abstract clas
Apart from the other suggestions (make it abstract or extend the interface) there is one further option:
Make all implementers of the interface extend a base class. This way, when you add methods to the interface you merely need to add default behaviour to the base class and class-specific behaviour to (hopefully) just a few implementers.
If you don't mind having no-op implementation of this method in all your classes and have control over all implementing classes, here is a very hacky way to do it with IntelliJ in 3 steps without going to each and every class:
Add your method to an interface
Select a method and invoke Refactor->Push Down... - your method declaration will appear in all the classes that implement this interface, but at least in my version of IntelliJ IDEA (11.0.2) they will have no implementation, e.g. void doSomething();, so select this definition and do a full-project Find & Replace to replace this string with your default implementation, for example,
#Override void doSomething() {}
Add your method to interface again.

Categories

Resources