Serializable interface in Java - java

I understand that the whole point of having an interface is to force the class that implements it to implement/define all the abstract methods in that interface.
However, in the process of Object Serialization in Java (conversion into byte stream), the class the object to be serialized is an instance of must implement the Serializable interface. However, I see no methods of the interface being defined. So, is that an interface with ZERO methods, if yes, is that even possible and if yes again, what is the purpose if it has no methods?

The Serializable interface is a marker interface. If a class implements it, the runtime system knows that the class is serializable.
In modern Java this effect could now be achieved with an annotation but they were not around at the time this interface was defined.

Yes such an interface is possible. It is called a marker interface. There are other interfaces like this also.
You can have a look at
http://mrbool.com/what-is-marker-interface-in-java/28557

As I already stated, purpose of interface with 0 methods is about pure contract.
Let me explain it in next example:
Let's say we have a simple data access layer composed of multiple interfaces like:
DeletableDao, InsertableDao, UpdatableDao etc.. and implementation class like DaoImpl:
Let's say we have entity class like this:
public Person implements DaoEntity {
private int id;
private String name;
// getters and setters
}
where DaoEntity is interface with 0 methods because of pure contract:
public DaoEntity {
}
and let's say that our DeletableDao looks like this:
public interface DeletableDao<T extends DaoEntity> {
void delete(T t);
}
and implementation class:
public DaoImpl implements DeletableDao<Person> {
public void delete(Person p) {
// Delete person
}
}
What this all means? What is a purpose of DaoEntity interface? It means that only instance of DaoEntity subclass can be passed to delete method and deleted.

Related

Using Marker interface for making methods more generic

For example,
I have a method in an abstract class with the following signature.
Set<CarRecommendation> generateRecommendations(String accountId){
// do something
}
To make the above method generic and compatible for different types of Recommendation, I'm thinking of using an empty interface and let CarRecommendation and BikeRecommendation implement it.
public interface Recommendation {
}
public class CarRecommendation implements Recommendation{
// more stuff
}
public class BikeRecommendation implements Recommendation{
// more stuff
}
so that I can change the method signature in the abstract class to the following
Set<? extends Recommendation> generateRecommendations(String accountId)
Is it a good practice to define marker interfaces for the sole purpose of making methods generic? If not, what would be a better approach? Thanks.

Interface and Abstract class share same method

Is this design really valid?
Legacy application code, so just trying to refactor if it's not necessary.
public interface Interface {
public void abc();
}
public abstract class abClass implements Interface{
#Override
public void abc(){
throw new UnsupportedOpException(NOT_IMPLEMENTED_MSG);
}
public class xyz extends abClass{
#Override
public void abc(){
.......//some code here
}
Can I get rid of the Interface? Not sure what's the original intention was behind this design. When would you want to have same methods in both interface and abstract classes which gets eventually overriden?
void abc(); must be implemented either by the abstract class or by the inherited classes...
there is no chance to get rid off that...
if you prefer, you can move the void abc(); as a method of the Abstract class...
redefined it and:
Block the overriding of ot by making it final.
or
delegate the responsability of the implementation to child classes by making it abstract too..
I think, from a functional programming perspective, it's fine as is. Having implements Interface just means the class must have a method with the same name. The fact that it is defined in abClass means that not only are you saying that all classes that inherit from abClass must have the interface, but also that you don't need to redefine it in every class, unless you wish to override.
So you don't actually define the method in Interface, but you do in abClass, and when you define the method in xyz, you're overriding the method in abClass.
An Interface should be used behind an abstract class when it offers something you need and that an abstract class cannot offer.
Create an interface for no concrete reasons but because you think that interface==OOP brings overhead and proves that you misunderstand what OOP is.
In your case, if in the applicative code, you notice that you can remove the interface behind the abstract class and that you have no real impact at compile time, you may wonder if the abstraction of the interface is not just an overhead. It may be useful as not useful. I will develop it.
Using an interface behind a abstract class opens implementation possibilities : you may benefit of this abstract class related with the interface but you can also implement the interface in concrete classes without benefiting of the abstract class, therefore as you wish. Writing an implementation from A to Z may be suitable as not suitable according to our needs.
Personally, I think that the interface is useful behind an abstract class in two cases :
the interface is common for at all types of target concrete classes but the
abstract class is relevant not for all types of target concrete classes.
For example when you implement a decorator, you have a common interface to represent both decorated classes and decorator classes.
The decorator classes have different logic and data from the decorated classes. So, our abstract class for decorator classes or for decorated classes may be different.
Here an simple example to represent Decorator for document.
Common interface :
public interface IDocumentInput {
void read();
byte[] getBytes();
String getStringContent();
}
decorated document :
public class DocumentInput implements IDocumentInput {
private byte[] bytes;
public DocumentInput(byte[] bytes) {
this.bytes = bytes;
}
public byte[] getBytes() {
return bytes;
}
public void read() {
}
public String getStringContent() {
return new String(getBytes(),StandardCharsets.UTF_8);
}
}
abstract class for decorators :
public abstract class AbstractDocumentInputDecorator implements IDocumentInput {
protected IDocumentInput document;
protected byte[] bytes;
public AbstractDocumentInputDecorator(IDocumentInput document) {
this.document = document;
}
public byte[] getBytes() {
return bytes;
}
public final String getStringContent() {
return new String(getBytes(),StandardCharsets.UTF_8);
}
}
Concrete decorator :
public class SecuredDocumentInputDecorator extends AbstractDocumentInputDecorator {
public SecuredDocumentInputDecorator(IDocumentInput document) {
super(document);
}
#Override
public void read() {
document.read();
processUnsecuring();
}
private void processUnsecuring() {
byte[] originalBytes = document.getBytes();
bytes = Base64.decodeBase64(originalBytes);
}
}
In this case, it seems logical to introduce an interface because the abstract class is not enough to represent common behavior and or data of all concrete classes.
You want to provide to developers the possibility to create their own implementation of the interface with or without relying on the abstract class implementation. In general, it's desirable when you create an open API.
Collections in JDK classes illustrate very well that.
Indeed, if you want to create interface/contract promoting extensibility, when you provide only an abstract class, developers which want to create their implementation are forced to use the abstract class even if they don't want. Which is not desirable.
You use a library which forces you to use interfaces. For example with EJB 3.0 and Spring in these first versions, using abstract class or class doesn't allow to benefit from some of their features.

Implementing interface with just one class or more classes

Maybe its answer is obvious for most of you but I am a bit confused when implementing an interface.
Should “just one implementation class” implement “the complete set of methods”?
Forex:
public class CCSImplementation implements CCS {
public void addComment (int submissionId,int customerId, String comment, Date date) { }
public void addGeneralComplaint (int submissionId, int customerId, String description, Date date) { }
and other methods…..}
Or
- More implementation classes such as
public class Comment implements CCS {
public void addComment() {}
}
and
public class GeneralComplaints implements CCS {
public void addGeneralComplaint(){}
}
implement the interface part by part taking into account of related methods? (---I got error when implement like these)
Since a reference says
One or more classes can implement that interface...
as I said I am a bit confused.
If the class is abstract, you don't have to implement all/any of the methods:
public abstract class Comment implements CCS {
public void addComment() {}
// addGeneralComplaint() is implied as abstract
}
Depending on your need, it would be perfectly valid to define such a class, where some of the methods are implemented, but subclasses are left to implement the rest of the interface's methods.
When a non-abstract class implements an interface it must provide implementations of all the exposed by the interface methods.
If we have an abstract class A, it can implement an interface without providing method implementations of the interface-exposed methods, since all of them are abstract by default. But when this class is subclassed by a non-abstract class B, the subclass must provide the implementations of the interface-exposed method signatures.
class Comment should extends Class GeneralComplaints
or
class GeneralComplaints should extends class Comment..
If it turns out that you are using an abstract class then you don't have to use everything. From my understanding you only want to implement something if you plan on using the provided methods. It was explained to me that an interface s provided so that the user doesn't forget to use methods in their class. Hope this helps.

Is there a way to guarantee an interface extends a class in Java?

Suppose I have the following situation:
public abstract class Vehicle {
public void turnOn() { ... }
}
public interface Flier {
public void fly();
}
Is there a way that I can guarantee that any class that implements Flier must also extend Vehicle? I don't want to make Flier an abstract class because I want to be able to mix a few other interfaces in a similar manner.
For instance:
// I also want to guarantee any class that implements Car must also implement Vehicle
public interface Car {
public void honk();
}
// I want the compiler to either give me an error saying
// MySpecialMachine must extend Vehicle, or implicitly make
// it a subclass of Vehicle. Either way, I want it to be
// impossible to implement Car or Flier without also being
// a subclass of Vehicle.
public class MySpecialMachine implements Car, Flier {
public void honk() { ... }
public void fly() { ... }
}
Java interfaces cannot extend classes, which makes sense since classes contain implementation details that cannot be specified within an interface..
The proper way to deal with this problem is to separate interface from implementation completely by turning Vehicle into an interface as well. The Car e.t.c. can extend the Vehicle interface to force the programmer to implement the corresponding methods. If you want to share code among all Vehicle instances, then you can use a (possibly abstract) class as a parent for any classes that need to implement that interface.
You could rearrange your classes and interfaces like this:
public interface IVehicle {
public void turnOn();
}
public abstract class Vehicle implements IVehicle {
public void turnOn() { ... }
}
public interface Flier extends IVehicle {
public void fly();
}
This way all implementations of Flier are guaranteed to implement the protocol of a vehicle, namely IVehicle.
If you have control on the Vehicle classes just extract Vehicle as an interface and then provide a base implementation.
If you have no control over Vehicle class, for example because it is part of a framework you are using or a third party library, it's not possible to do in Java.
The closest thing you can do is using Generics multiple wildcards notation.
<T extends Vehicle & Car>
But you can't really apply it directly to Car unless you do something like this:
public interface Car<T extends Vehicle & Car>() {
T self();
}
Which is bot weird and do not enforce the self method to actually return self, it's just a strong hint/suggestion.
You would implement a Car like this:
public class CitroenC3 extends Vehicle implements Car<CitroenC3> {
#Override
public CitroenC3 self() {
return this;
}
}
one can use a Car<?> like this:
Car<?> car = obtainCarInSomeWay();
Vehicle v = car.self();
Car c = car.self();
they should be both valid syntax.
What the compiler enforce here is that what you specify in Car<WHICH> as WHICH must both extend Vehicle and implement Car. And by adding self() you are saying to the programmer that the T object is supposed to be the object itself, thus forcing the wildcard instance to match the class if he want to be compliant with the specification.
in Java 8 you can even define a default implementation for the self method.
I also wish there was a better way to handle something like this.
It's a strange requirement, but you can accomplish something of the sort with Generics:
<T extends MyInterface & MyAbstractClass>
This question shows that you haven't grasped the essence of interface and class. Forgetting the concrete Java syntax right now, all you need to understand first is that: interface is a set of protocol, which should be implementation-agnostic. It makes no sense to let an interface extend a class(which is implementation-oriented).
Back to your concrete question, if you want to guarantee that a Flier is always a kind of Vehicle, just change the latter to an interface and let former extends it(It does make sense to extend one protocol from the other protocol). After that, you may create any class(abstract or concrete) that implements Vehicle or Flier.
Define a new Package
Create a new interface (ie. HiddenOne) with scope "default" with a method "implementMe(HiddenOne)"
Move Vehicle and Flier to the new Package.
Inherit Vehicle and Flier from HiddenOne
Implement the method implementMe in Vehicle.
Now: Whenever you like to implement from "Flier" you must extends from Vehicle !
(because only Vehicle can implement implementMe).
This is tricky but works great.

Interfaces usage

Can you have a class which implements an interface, and choose whether to use the methods in the interface during instantiation of this class? Therefore having object A which uses the interface and object B which does not use it.
Thanks
Updated:
Assuming you have a Professor class and this class implements an interface called Employer, which has employ(rAssist x) abstract method.
Now I want to instantiated 2 objects from the Professor class implementing this interface Object A - Professor can employ a research assistant and Object B - Professor cannot employ research assistants.
Can you have a class which implements an interface, and choose whether to use the methods in the interface during instantiation of this class?
No, if class C implements the interface, then all instances of C will provide the methods declared in the interface.
What you can do is something like
class MyClass implements MyInterface {
#Override
void interfaceMethod() {
System.out.println("Interface method");
}
}
and then do
MyClass x = new MyClass();
MyClass y = new MyClass() {
#Override
void interfaceMethod() {
throw new UnsupportedOperationException();
}
};
In effect, x supports the use of interfaceMethod while y does not. Note however that...
The usage of y.interfaceMethod is not prevented at compile-time, i.e. it will not be enforced by the type system.
With this solution, you are in fact creating an (anonymous) subclass of MyClass and assigning an instance of it to y.
Do you mean you want class A and Class B to implement a common Interface but you dont want to implement all methods in Class B?
An Interface in simple terms means it is sort of a contract and all the classes which implement it should follow that contract.So if you want Class B to implement the interface , Class B should also follow the same contract. But if you dont want to implement any methos you can always do this.
class ISampleInterface {
void sampleMethod();
void optionalMethod();
}
Class A implements ISampleInterface {
void sampleMethod() {
//Your Implementation
}
void optionalMethod() {
//Your Implementation
}
}
class B implements ISampleInterface {
void sampleMethod() {
//Your Implementation
}
void optionalMethod() {
throw new UnsupportedMethodException();
}
}
No, that's not the point of an Interface.
An Interface is contract that guarantees that implementations WILL implement it's signature
The idea of interface is to establish a obligation for the class that implements the interface.
If your's is a requirement, you can use the java.lang.reflect.Method reflection class to change the visibility of the method at runtime. However, this is not a clean way.
1. Interfaces were introduced in Java because Multiple Inheritance was not allowed in Java.
2. But as far as Design Pattern are concerned, following are the uses..
- To implement certain Roles.
Consider Dog a Super class, but then Pet dog and Wild dog can be interfaces, which
can be implemented by the Sub Classes of Dog class.
- Used when Behaviors keeps changing.
Consider you have a Class Drawing, and paint method() in it, now paint can be stroking, shading, etc...
You must Encapsulate such behaviors in an Interface or an Abstract class.

Categories