Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Interfaces provide specific meaning to objects in Java

I have a doubt about Interfaces in JAVA:

When a class implements an interface, does anything happen to it if it does not implement its methods? Merely implementing the interface , does it provide any change of meaning to the class ?

For example I have two classes, Test1 and Test2

public class Test1 implements Serializable { 
}


public class Test2 {          
}

Except for the fact that Test1 implements Serializable, the classes Test1 and Test2 are identical. In that case would there be any difference between the functionalities/properties of objects of Test1 and Test2? Would it be possible to break down objects of Test1 class into bytes (just because class Test1implements Serializable)?

If yes, then that means implementing an interface provides some additional meaning to the objects of that class?

like image 542
Ran N Avatar asked Apr 07 '26 15:04

Ran N


1 Answers

Straight from documentaion of Serializable -

Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.

Link

Q1> In that case would there be any difference between the functionalities/properties of objects of Test1 and Test2?

Serializable is marker interface, which means there no method or field.

Q2> Would it be possible to break down Objects of Test1 class into bytes (just because class Test1 implements Serializable?
Yes.

Q3> If yes, then that means implementing an interface provides some additional meaning to the objects of that class?

Object Serialization produces a stream with information about the Java classes for the objects which are being saved. For serializable objects, sufficient information is kept to restore those objects even if a different (but compatible) version of the implementation of the class is present.

Thhe class can optionally define the following methods:

  • A writeObject method to control what information is saved or to append additional information to the stream

  • A readObject method either to read the information written by the corresponding writeObject method or to update the state of the object after it has been restored

  • A writeReplace method to allow a class to nominate a replacement object to be written to the stream

Link

like image 114
Subhrajyoti Majumder Avatar answered Apr 10 '26 06:04

Subhrajyoti Majumder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!