<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Naresh Joshi</title>
    <description>The latest articles on DEV Community by Naresh Joshi (@njnareshjoshi).</description>
    <link>https://dev.to/njnareshjoshi</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F170097%2Ff4965469-aa9b-40e8-a5a6-29d39cd7f838.jpeg</url>
      <title>DEV Community: Naresh Joshi</title>
      <link>https://dev.to/njnareshjoshi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/njnareshjoshi"/>
    <language>en</language>
    <item>
      <title>Java Integer Cache: Why Integer.valueOf(127) == Integer.valueOf(127) Is True</title>
      <dc:creator>Naresh Joshi</dc:creator>
      <pubDate>Thu, 16 Jan 2020 04:30:29 +0000</pubDate>
      <link>https://dev.to/njnareshjoshi/java-integer-cache-why-integer-valueof-127-integer-valueof-127-is-true-643</link>
      <guid>https://dev.to/njnareshjoshi/java-integer-cache-why-integer-valueof-127-integer-valueof-127-is-true-643</guid>
      <description>&lt;p&gt;In an interview, one of my friends was asked that if we have two Integer objects, &lt;code&gt;Integer a = 127; Integer b = 127;&lt;/code&gt; Why &lt;code&gt;a == b&lt;/code&gt; evaluate to &lt;code&gt;true&lt;/code&gt; when both are holding two separate objects? In this article, I will try to answer this question and also try to explain the answer.  &lt;/p&gt;

&lt;h4&gt;
  
  
  Short Answer
&lt;/h4&gt;

&lt;p&gt;The short answer to this question is, direct assignment of an &lt;code&gt;int&lt;/code&gt; literal to an &lt;code&gt;Integer&lt;/code&gt; reference is an example of auto-boxing concept where the literal value to object conversion code is handled by the compiler, so during compilation phase compiler converts &lt;code&gt;Integer a = 127;&lt;/code&gt; to &lt;code&gt;Integer a = Integer.valueOf(127);&lt;/code&gt;.  &lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Integer&lt;/code&gt; class maintains an internal IntegerCache for integers which by default ranges from &lt;code&gt;-128 to 127&lt;/code&gt; and &lt;code&gt;Integer.valueOf()&lt;/code&gt; method returns objects of mentioned range from that cache. So &lt;code&gt;a == b&lt;/code&gt; returns true because &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; both are pointing to the same object.&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/rkpDuCFB_bQ"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h4&gt;
  
  
  Long Answer
&lt;/h4&gt;

&lt;p&gt;In order to understand the short answer let's first understand the Java types, all types in Java lies under two categories  &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Primitive Types:&lt;/strong&gt; There are 8 primitive types (byte, short, int, long, float, double, char and boolean) in Java which holds their values directly in the form of binary bits.&lt;br&gt;&lt;br&gt;
For example, &lt;code&gt;int a = 5; int b = 5;&lt;/code&gt; here &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; directly holds the binary value of 5 and if we try to compare &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; using &lt;code&gt;a == b&lt;/code&gt; we are actually comparing &lt;code&gt;5 == 5&lt;/code&gt; which returns true.  &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Reference Types:&lt;/strong&gt; All types other than primitive types lies under the category of reference types e.g. Classes, Interfaces, Enums, Arrays etc. and reference types holds the address of the object instead of the object itself.&lt;br&gt;&lt;br&gt;
For example, &lt;code&gt;Integer a = new Integer(5); Integer b = new Integer(5)&lt;/code&gt;, here a and b do not hold the binary value of &lt;code&gt;5&lt;/code&gt; instead &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; holds memory addresses of two separate objects where both objects contain a value &lt;code&gt;5&lt;/code&gt;. So if we try to compare &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; using &lt;code&gt;a == b, &lt;/code&gt;we are actually comparing those two separate memory addresses hence we get &lt;code&gt;false&lt;/code&gt;, to perform actual equality on &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; we need to perform &lt;code&gt;a.euqals(b)&lt;/code&gt;.  &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Reference types are further divided into 4 categories &lt;a href="https://programmingmitra.com/2016/05/types-of-references-in-javastrong-soft.html" rel="noopener noreferrer"&gt;Strong, Soft, Weak and Phantom References&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;And we know that Java provides wrapper classes for all primitive types and support auto-boxing and auto-unboxing.  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Example of auto-boxing, here c is a reference type
Integer c = 128; // Compiler converts this line to Integer c = Integer.valueOf(128); 

// Example of auto-unboxing, here e is a primitive type
int e = c; // Compiler converts this line to int e = c.intValue();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now if we create two integer objects &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b,&lt;/code&gt; and try to compare them using the equality operator &lt;code&gt;==&lt;/code&gt;, we will get &lt;code&gt;false&lt;/code&gt; because both references are holding different-different objects  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Integer a = 128; // Compiler converts this line to Integer a = Integer.valueOf(128);
Integer b = 128; // Compiler converts this line to Integer b = Integer.valueOf(128);

System.out.println(a == b); // Output -- false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;But if we assign the value &lt;code&gt;127&lt;/code&gt; to both &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; and try to compare them using the equality operator &lt;code&gt;==&lt;/code&gt;, we will get &lt;code&gt;true&lt;/code&gt; why?  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Integer a = 127; // Compiler converts this line to Integer a = Integer.valueOf(127);
Integer b = 127; // Compiler converts this line to Integer b = Integer.valueOf(127);

System.out.println(a == b); // Output -- true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As we can see in the code that we are assigning different objects to &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; but &lt;code&gt;a == b&lt;/code&gt; can return true only if both &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; are pointing to the same object.  &lt;/p&gt;

&lt;p&gt;So how is the comparison returning true? what's actually happening here? are &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; pointing to the same object?&lt;/p&gt;

&lt;p&gt;Well till now we know that the code &lt;code&gt;Integer a = 127;&lt;/code&gt; is an example of auto-boxing and compiler automatically converts this line to &lt;code&gt;Integer a = Integer.valueOf(127);&lt;/code&gt;.  &lt;/p&gt;

&lt;p&gt;So it is the &lt;code&gt;Integer.valueOf()&lt;/code&gt; method which is returning these integer objects which means this method must be doing something under the hood.  &lt;/p&gt;

&lt;p&gt;And if we take a look at the source code of &lt;code&gt;Integer.valueOf()&lt;/code&gt; method, we can clearly see that if the passed int literal &lt;code&gt;i&lt;/code&gt; is greater than &lt;code&gt;IntegerCache.low&lt;/code&gt; and less than &lt;code&gt;IntegerCache.high &lt;/code&gt;then the method returns Integer objects from &lt;code&gt;IntegerCache&lt;/code&gt;. Default values for &lt;code&gt;IntegerCache.low&lt;/code&gt; and &lt;code&gt;IntegerCache.high&lt;/code&gt; are &lt;code&gt;-128&lt;/code&gt; and &lt;code&gt;127&lt;/code&gt; respectively.&lt;/p&gt;

&lt;p&gt;In other words, instead of creating and returning new integer objects, &lt;code&gt;Integer.valueOf()&lt;/code&gt; method returns Integer objects from an internal &lt;code&gt;IntegerCache&lt;/code&gt; if the passed int literal is greater than &lt;code&gt;-128&lt;/code&gt; and less than &lt;code&gt;127&lt;/code&gt;.  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
 * Returns an {@code Integer} instance representing the specified
 * {@code int} value.  If a new {@code Integer} instance is not
 * required, this method should generally be used in preference to
 * the constructor {@link #Integer(int)}, as this method is likely
 * to yield significantly better space and time performance by
 * caching frequently requested values.
 *
 * This method will always cache values in the range -128 to 127,
 * inclusive, and may cache other values outside of this range.
 *
 * @param  i an {@code int} value.
 * @return an {@code Integer} instance representing {@code i}.
 * @since  1.5
 */
 public static Integer valueOf(int i) {
     if (i &amp;gt;= IntegerCache.low &amp;amp;&amp;amp; i &amp;lt;= IntegerCache.high)
         return IntegerCache.cache[i + (-IntegerCache.low)];
     return new Integer(i);
 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Java caches integer objects which fall into -128 to 127 range because this range of integers gets used a lot in day to day programming which indirectly saves some memory.  &lt;/p&gt;

&lt;p&gt;As you can see in the following image &lt;code&gt;Integer&lt;/code&gt; class maintains an inner static &lt;code&gt;IntegerCache&lt;/code&gt; class which acts as the cache and holds integer objects from -128 to 127 and that's why when we try to get integer object for &lt;code&gt;127&lt;/code&gt; we always get the same object.  &lt;/p&gt;

&lt;p&gt;&lt;a href="//3.bp.blogspot.com/-ngjlYvWfXDw/W_qTudu9SAI/AAAAAAAASFk/9zHm0pNhRJQ-lANyhzXBgQSA3vB87OssQCK4BGAYYCw/s1600/integer-cache-src-code.jpeg"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2F3.bp.blogspot.com%2F-ngjlYvWfXDw%2FW_qTudu9SAI%2FAAAAAAAASFk%2F9zHm0pNhRJQ-lANyhzXBgQSA3vB87OssQCK4BGAYYCw%2Fs1600%2Finteger-cache-src-code.jpeg" title="integer-cache-sourcec-code" alt="integer-cache-source-code"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The cache is initialized on the first usage when the class gets loaded into memory because of the &lt;code&gt;static block&lt;/code&gt;. The max range of the cache can be controlled by the &lt;code&gt;-XX:AutoBoxCacheMax&lt;/code&gt; JVM option.  &lt;/p&gt;

&lt;p&gt;This caching behavior is not applicable to &lt;code&gt;Integer&lt;/code&gt; objects only, similar to &lt;code&gt;Integer.IntegerCache&lt;/code&gt; we also have &lt;code&gt;ByteCache&lt;/code&gt;, &lt;code&gt;ShortCache&lt;/code&gt;, &lt;code&gt;LongCache&lt;/code&gt;, &lt;code&gt;CharacterCache&lt;/code&gt; for &lt;code&gt;Byte&lt;/code&gt;, &lt;code&gt;Short&lt;/code&gt;, &lt;code&gt;Long&lt;/code&gt;, &lt;code&gt;Character&lt;/code&gt; respectively.&lt;/p&gt;

&lt;p&gt;Byte, Short and Long have a fixed range for caching between –127 to 127 (inclusive) but for Character, the range is from 0 to 127 (inclusive). The range can be modified via argument only for Integer but not for others.  &lt;/p&gt;

&lt;p&gt;You can find the complete source code for this article on this &lt;a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/IntegerCacheExample.java" rel="noopener noreferrer"&gt;Github Repository&lt;/a&gt; and please feel free to provide your valuable feedback.&lt;/p&gt;

</description>
      <category>java</category>
    </item>
    <item>
      <title>Java Serialization Magic Methods And Their Uses With Example</title>
      <dc:creator>Naresh Joshi</dc:creator>
      <pubDate>Mon, 13 Jan 2020 15:22:44 +0000</pubDate>
      <link>https://dev.to/njnareshjoshi/java-serialization-magic-methods-and-their-uses-with-example-4beo</link>
      <guid>https://dev.to/njnareshjoshi/java-serialization-magic-methods-and-their-uses-with-example-4beo</guid>
      <description>&lt;p&gt;In a previous article &lt;a href="https://www.programmingmitra.com/2019/08/what-is-serialization-everything-about-java-serialization-explained-with-example.html" rel="noopener noreferrer"&gt;Everything You Need to Know About Java Serialization&lt;/a&gt;, we discussed how serializability of a class is enabled by implementing the &lt;code&gt;Serializable&lt;/code&gt; interface. If our class does not implement &lt;code&gt;Serializable&lt;/code&gt; interface or if it is having a reference to a non &lt;code&gt;Serializable&lt;/code&gt; class then JVM will throw &lt;code&gt;NotSerializableException&lt;/code&gt;.  &lt;/p&gt;

&lt;p&gt;All subtypes of a serializable class are themselves serializable and &lt;code&gt;Externalizable&lt;/code&gt; interface also extends Serializable. So even if we &lt;a href="https://www.programmingmitra.com/2019/08/how-to-customize-serialization-in-java-by-using-externalizable-interface.html" rel="noopener noreferrer"&gt;customize our serialization process using Externalizable&lt;/a&gt; our class is still a &lt;code&gt;Serializable&lt;/code&gt;.  &lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Serializable&lt;/code&gt; interface is a marker interface which has no methods or fields and it works like a flag for the JVM. The Java serialization process provided by &lt;code&gt;ObjectInputStream&lt;/code&gt; and &lt;code&gt;ObjectOutputStream&lt;/code&gt; classes are fully controlled by the JVM.&lt;/p&gt;

&lt;p&gt;But what if we want to add some additional logic to enhance this normal process, for example, we may want to encrypt/decrypt our sensitive information before serializing/deserializing it. Java provides us with some additional methods for this purpose which we are going to discuss in this blog.  &lt;/p&gt;

&lt;p&gt;&lt;a href="//1.bp.blogspot.com/-PY8NeWXIT9M/XWj3YDAe34I/AAAAAAAAV8Y/vydjL3tYMYkNxl4myqCGr65QYc9KVBbewCK4BGAYYCw/s1600/Java-Serialization-Magic-Methods-And-Their-Uses.png"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2F1.bp.blogspot.com%2F-PY8NeWXIT9M%2FXWj3YDAe34I%2FAAAAAAAAV8Y%2FvydjL3tYMYkNxl4myqCGr65QYc9KVBbewCK4BGAYYCw%2Fs1600%2FJava-Serialization-Magic-Methods-And-Their-Uses.png" title="Java-Serialization-Magic-Methods-And-Their-Uses" alt="Java-Serialization-Magic-Methods-And-Their-Uses"&gt;&lt;/a&gt;  &lt;/p&gt;

&lt;h2&gt;
  
  
  writeObject and readObject methods
&lt;/h2&gt;

&lt;p&gt;Serializable classes that want to customize or add some additional logic to enhance the normal serialization/deserialization process should provide &lt;code&gt;writeObject&lt;/code&gt; and &lt;code&gt;readObject&lt;/code&gt; methods with these exact signatures:  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;private void writeObject(java.io.ObjectOutputStream out) throws IOException&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These methods are already discussed in great details under article &lt;a href="https://www.programmingmitra.com/2019/08/what-is-serialization-everything-about-java-serialization-explained-with-example.html" rel="noopener noreferrer"&gt;Everything You Need to Know About Java Serialization&lt;/a&gt;.  &lt;/p&gt;

&lt;h2&gt;
  
  
  readObjectNoData method
&lt;/h2&gt;

&lt;p&gt;As described in Java docs of &lt;code&gt;Serializable&lt;/code&gt; class, if we want to initialize the state of the object for its particular class in the event that the serialization stream does not list the given class as a superclass of the object being deserialized then we should provide &lt;code&gt;writeObject&lt;/code&gt; and &lt;code&gt;readObject&lt;/code&gt; methods with these exact signatures:  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;private void readObjectNoData() throws ObjectStreamException&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This may occur in cases where the receiving party uses a different version of the deserialized instance's class than the sending party, and the receiver's version extends classes that are not extended by the sender's version. This may also occur if the serialization stream has tampered; hence, readObjectNoData is useful for initializing deserialized objects properly despite a "hostile" or incomplete source stream.  &lt;/p&gt;

&lt;p&gt;Each serializable class may define its own &lt;code&gt;readObjectNoData&lt;/code&gt; method. If a serializable class does not define a &lt;code&gt;readObjectNoData&lt;/code&gt; method, then in the circumstances listed above the fields of the class will be initialized to their default values.  &lt;/p&gt;

&lt;h2&gt;
  
  
  writeReplace and readResolve methods
&lt;/h2&gt;

&lt;p&gt;Serializable classes that need to designate an alternative object to be used when writing an object to the stream should provide this special method with the exact signature:  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And Serializable classes that need to designate a replacement when an instance of it is read from the stream should provide this special method with the exact signature:  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Basically, the &lt;code&gt;writeReplace&lt;/code&gt; method allows the developer to provide a replacement object that will be serialized instead of the original one. And the &lt;code&gt;readResolve&lt;/code&gt; method is used during deserialization process to replace the de-serialized object by another one of our choices.  &lt;/p&gt;

&lt;p&gt;One of the main usages of writeReplace and readResolve methods is to implement the singleton design pattern with Serialized classes. We know that the &lt;a href="https://www.programmingmitra.com/2016/05/different-ways-to-create-objects-in-java-with-example.html" rel="noopener noreferrer"&gt;deserialization process creates a new object every time&lt;/a&gt; and it can also be &lt;a href="https://www.programmingmitra.com/2019/08/how-to-deep-clone-an-object-using-java-in-memory-serialization.html" rel="noopener noreferrer"&gt;used as a method to deeply clone an object&lt;/a&gt;, which is not good if we have to make our class singleton.  &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;You can read more about Java cloning and serialization on &lt;a href="https://www.programmingmitra.com/search/label/Java%20Cloning" rel="noopener noreferrer"&gt;Java Cloning&lt;/a&gt; and &lt;a href="https://www.programmingmitra.com/search/label/Serialization" rel="noopener noreferrer"&gt;Java Serialization&lt;/a&gt; topics.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The method &lt;code&gt;readResolve&lt;/code&gt; is called after &lt;code&gt;readObject&lt;/code&gt; has returned (conversely &lt;code&gt;writeReplace&lt;/code&gt; is called before &lt;code&gt;writeObject&lt;/code&gt; and probably on a different object). The object the method returns replaces &lt;code&gt;this&lt;/code&gt; object returned to the user of &lt;code&gt;ObjectInputStream.readObject&lt;/code&gt; and any further back-references to the object in the stream. We can use the writeReplace method to replace serializing object with null so nothing will be serialized and then use the readResolve method to replace the deserialized object with the singleton instance.  &lt;/p&gt;

&lt;h2&gt;
  
  
  validateObject method
&lt;/h2&gt;

&lt;p&gt;If we want to perform certain validations on some of our fields we can do that by implementing &lt;code&gt;ObjectInputValidation&lt;/code&gt; interface and overriding &lt;code&gt;validateObject&lt;/code&gt; method from it.  &lt;/p&gt;

&lt;p&gt;Method &lt;code&gt;validateObject&lt;/code&gt; will automatically get called when we register this validation by calling &lt;code&gt;ObjectInputStream.registerValidation(this, 0)&lt;/code&gt; from &lt;code&gt;readObject&lt;/code&gt; method. It is very useful to verify the stream has not been tampered with, or that the data makes sense before handing it back to your application.  &lt;/p&gt;

&lt;p&gt;Below example covers code for all above methods  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class SerializationMethodsExample {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Employee emp = new Employee("Naresh Joshi", 25);
        System.out.println("Object before serialization: " + emp.toString());

        // Serialization
        serialize(emp);

        // Deserialization
        Employee deserialisedEmp = deserialize();
        System.out.println("Object after deserialization: " + deserialisedEmp.toString());


        System.out.println();

        // This will print false because both object are separate
        System.out.println(emp == deserialisedEmp);

        System.out.println();

        // This will print false because both `deserialisedEmp` and `emp` are pointing to same object,
        // Because we replaced de-serializing object in readResolve method by current instance
        System.out.println(Objects.equals(emp, deserialisedEmp));
    }

    // Serialization code
    static void serialize(Employee empObj) throws IOException {
        try (FileOutputStream fos = new FileOutputStream("data.obj");
             ObjectOutputStream oos = new ObjectOutputStream(fos))
        {
            oos.writeObject(empObj);
        }
    }

    // Deserialization code
    static Employee deserialize() throws IOException, ClassNotFoundException {
        try (FileInputStream fis = new FileInputStream("data.obj");
             ObjectInputStream ois = new ObjectInputStream(fis))
        {
            return (Employee) ois.readObject();
        }
    }
}

class Employee implements Serializable, ObjectInputValidation {
    private static final long serialVersionUID = 2L;

    private String name;
    private int age;

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // With ObjectInputValidation interface we get a validateObject method where we can do our validations.
    @Override
    public void validateObject() {
        System.out.println("Validating age.");

        if (age &amp;lt; 18 || age &amp;gt; 70)
        {
            throw new IllegalArgumentException("Not a valid age to create an employee");
        }
    }

    // Custom serialization logic,
    // This will allow us to have additional serialization logic on top of the default one e.g. encrypting object before serialization.
    private void writeObject(ObjectOutputStream oos) throws IOException {
        System.out.println("Custom serialization logic invoked.");
        oos.defaultWriteObject(); // Calling the default serialization logic
    }

    // Replacing de-serializing object with this,
    private Object writeReplace() throws ObjectStreamException {
        System.out.println("Replacing serialising object by this.");
        return this;
    }

    // Custom deserialization logic
    // This will allow us to have additional deserialization logic on top of the default one e.g. performing validations, decrypting object after deserialization.
    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
        System.out.println("Custom deserialization logic invoked.");

        ois.registerValidation(this, 0); // Registering validations, So our validateObject method can be called.

        ois.defaultReadObject(); // Calling the default deserialization logic.
    }

    // Replacing de-serializing object with this,
    // It will will not give us a full proof singleton but it will stop new object creation by deserialization.
    private Object readResolve() throws ObjectStreamException {
        System.out.println("Replacing de-serializing object by this.");
        return this;
    }

    @Override
    public String toString() {
        return String.format("Employee {name='%s', age='%s'}", name, age);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You can find the complete source code for this article on this &lt;a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/SerializationMethodsExample.java" rel="noopener noreferrer"&gt;Github Repository&lt;/a&gt; and please feel free to provide your valuable feedback.&lt;/p&gt;

</description>
      <category>java</category>
      <category>serialization</category>
    </item>
    <item>
      <title>Why an outer Java class can’t be static</title>
      <dc:creator>Naresh Joshi</dc:creator>
      <pubDate>Tue, 24 Dec 2019 14:11:29 +0000</pubDate>
      <link>https://dev.to/njnareshjoshi/why-an-outer-java-class-can-t-be-static-1fef</link>
      <guid>https://dev.to/njnareshjoshi/why-an-outer-java-class-can-t-be-static-1fef</guid>
      <description>&lt;p&gt;&lt;a href="https://programmingmitra.com/2016/10/why-a-java-class-can-not-be-private-or-protected.html"&gt;In a previous blog&lt;/a&gt;, I talked about why we can not define an outer class using private or protected keywords. If you have not read it, please go ahead and give it a look.  &lt;/p&gt;

&lt;p&gt;In this article I will talk what is the use of the static keyword, why an outer Java class can’t be static, why it is not allowed in Java to define a static outer class. In order to understand that first, we need to understand what is the static keyword used for, what purpose it solves and how does it work.  &lt;/p&gt;

&lt;h4&gt;
  
  
  What does static keyword do
&lt;/h4&gt;

&lt;p&gt;Every Java programmer knows that if we need to define some behaviour (method) or state (field) which will be common to all objects we define it as static. Because static content (behaviour or state) does not belong to any particular instance or object, it will common to all objects and all objects are free to change any static field and every change will be visible to every object.  &lt;/p&gt;

&lt;p&gt;We do not need to create an object of the class to access a static field or method, we can directly refer a static field or method by using class name and dot operator e.g. Class.forName(“ClassName”).&lt;br&gt;&lt;br&gt;
This happens because JVM creates a Class level object for every class when Classloader loads the class into memory. And all static content of that class belongs this Class object and all other objects of that class refer to this class level object for all static content. A class-level object is actually an object of java.lang.Class and it is referred by your_class_name.class syntax.  &lt;/p&gt;

&lt;p&gt;For Example for the below statement, two objects will get created  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Employee emp =  new Employee();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;One is ‘emp’ (the new Employee();) itself and another one is the ‘class level object’ of Employee class which will get created while JVM will load Employee class into memory and we can refer it by Employee.class. And this class level object holds all the static content of the Employee class either it is a variable or method. If we are accessing any static content through emp object it automatically points to Employee.class object to access that.  &lt;/p&gt;

&lt;p&gt;That is the reason why a static variable got changed for every object even if we change it for a single emp object because all emp objects are pointing same copy of that variable from Employee.class object, for more information read &lt;a href="https://programmingmitra.com/2016/06/why-java-is-purely-object-oriented-or-why-not.html"&gt;Why Java is Purely Object-Oriented Language Or Why Not&lt;/a&gt;.  &lt;/p&gt;

&lt;h4&gt;
  
  
  Why an outer Java class can’t be static
&lt;/h4&gt;

&lt;p&gt;From above we can conclude that we should define members as static which  &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Should be common to all objects of the class.&lt;/li&gt;
&lt;li&gt; Should belong to the class and accessible by class name.&lt;/li&gt;
&lt;li&gt; Should not need an object of a class to access them.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now suppose we are defining an outer class as static and suppose we are allowed to do so. Will this serve any purpose or provide any advantage to a developer or it will create ambiguity and complications for both developers and language creators?  &lt;/p&gt;

&lt;p&gt;Let’s check, defining an outer class as static will serve purposes which we have defined above or not?  &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Every class is already common to all of its objects and there is no need to make it static to become available to all of its objects.&lt;/li&gt;
&lt;li&gt; We need a class name to access its static members because these members are part of class while an outer class is part of the package and we can directly access the class by just writing package_name.class_name (similar to class_name.static_field_name), So again there is no need to do which is already there by default.&lt;/li&gt;
&lt;li&gt; We do not need any object to access a class if it is visible, we can simply write package_name.class_name to access it. And by definition, a class is a blueprint for its objects and we create a class to create objects from it (exception will always be there e.g. java.lang.Math), again there is no need to define an outer class as static.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;From the above points, we can say Java creators had not allowed an outer class to be static because there is no need to make it static. Allowing to make the outer class static will only increase complications, ambiguity and duplicity.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>What is Serialization? Everything You Need to Know About Java Serialization Explained With Example</title>
      <dc:creator>Naresh Joshi</dc:creator>
      <pubDate>Fri, 30 Aug 2019 16:42:45 +0000</pubDate>
      <link>https://dev.to/njnareshjoshi/what-is-serialization-everything-you-need-to-know-about-java-serialization-explained-with-example-9mj</link>
      <guid>https://dev.to/njnareshjoshi/what-is-serialization-everything-you-need-to-know-about-java-serialization-explained-with-example-9mj</guid>
      <description>&lt;p&gt;In a previous article, we looked at &lt;a href="https://www.programmingmitra.com/2016/05/different-ways-to-create-objects-in-java-with-example.html"&gt;5 different ways to create objects in java&lt;/a&gt;, I have explained how deserialising a serialised object creates a new object and in this blog, I am going to discuss Serialization and Deserialization in details.  &lt;/p&gt;

&lt;p&gt;We will use below &lt;code&gt;Employee&lt;/code&gt; class object as an example for the explanation  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// If we use Serializable interface, static and transient variables do not get serialize
class Employee implements Serializable {

    // This serialVersionUID field is necessary for Serializable as well as Externalizable to provide version control,
    // Compiler will provide this field if we do not provide it which might change if we modify the class structure of our class, and we will get InvalidClassException,
    // If we provide value to this field and do not change it, serialization-deserialization will not fail if we change our class structure.
    private static final long serialVersionUID = 2L;

    private final String firstName; // Serialization process do not invoke the constructor but it can assign values to final fields
    private transient String middleName; // transient variables will not be serialized, serialised object holds null
    private String lastName;
    private int age;
    private static String department; // static variables will not be serialized, serialised object holds null

    public Employee(String firstName, String middleName, String lastName, int age, String department) {
        this.firstName = firstName;
        this.middleName = middleName;
        this.lastName = lastName;
        this.age = age;
        Employee.department = department;

        validateAge();
    }

    private void validateAge() {
        System.out.println("Validating age.");

        if (age &amp;lt; 18 || age &amp;gt; 70) {
            throw new IllegalArgumentException("Not a valid age to create an employee");
        }
    }

    @Override
    public String toString() {
        return String.format("Employee {firstName='%s', middleName='%s', lastName='%s', age='%s', department='%s'}", firstName, middleName, lastName, age, department);
    }

  // Custom serialization logic,
    // This will allow us to have additional serialization logic on top of the default one e.g. encrypting object before serialization
    private void writeObject(ObjectOutputStream oos) throws IOException {
        System.out.println("Custom serialization logic invoked.");
        oos.defaultWriteObject(); // Calling the default serialization logic
    }

    // Custom deserialization logic
    // This will allow us to have additional deserialization logic on top of the default one e.g. decrypting object after deserialization
    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
        System.out.println("Custom deserialization logic invoked.");

        ois.defaultReadObject(); // Calling the default deserialization logic

        // Age validation is just an example but there might some scenario where we might need to write some custom deserialization logic
        validateAge();
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  What are Serialization and Deserialization
&lt;/h2&gt;

&lt;p&gt;In Java, we create several objects which live and die accordingly and every object will certainly die when the JVM dies but sometimes we might want to reuse an object between several JVMs or we might want to transfer an object to another machine over the network.  &lt;/p&gt;

&lt;p&gt;Well, &lt;strong&gt;serialization&lt;/strong&gt; allows us to convert the state of an object into a byte stream, which then can be saved into a file on the local disk or sent over the network to any other machine. And &lt;strong&gt;deserialization&lt;/strong&gt; allows us to reverse the process, which means reconverting the serialized byte stream to an object again.&lt;/p&gt;

&lt;p&gt;In simple words, object &lt;strong&gt;serialization&lt;/strong&gt; is the process of saving an object's state to a sequence of bytes and &lt;strong&gt;deserialization&lt;/strong&gt; is the process of reconstructing an object from those bytes. Generally, the complete process is called &lt;strong&gt;serialization&lt;/strong&gt; but I think it is better to classify both as separate for more clarity.  &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The serialization process is platform independent, an object serialized on one platform can be deserialized on a different platform.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To serialize and deserialize our object to a file we need to call &lt;code&gt;ObjectOutputStream.writeObject()&lt;/code&gt; and &lt;code&gt;ObjectInputStream.readObject()&lt;/code&gt; as done in the following code:  &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class SerializationExample {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Employee empObj = new Employee("Shanti", "Prasad", "Sharma", 25, "IT");
        System.out.println("Object before serialization  =&amp;gt; " + empObj.toString());

        // Serialization
        serialize(empObj);

        // Deserialization
        Employee deserialisedEmpObj = deserialize();
        System.out.println("Object after deserialization =&amp;gt; " + deserialisedEmpObj.toString());
    }

    // Serialization code
    static void serialize(Employee empObj) throws IOException {
        try (FileOutputStream fos = new FileOutputStream("data.obj");
             ObjectOutputStream oos = new ObjectOutputStream(fos))
        {
            oos.writeObject(empObj);
        }
    }

    // Deserialization code
    static Employee deserialize() throws IOException, ClassNotFoundException {
        try (FileInputStream fis = new FileInputStream("data.obj");
             ObjectInputStream ois = new ObjectInputStream(fis))
        {
            return (Employee) ois.readObject();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Only classes which implement Serializable can be serialized
&lt;/h2&gt;

&lt;p&gt;Similar to the Cloneable interface for &lt;a href="https://www.programmingmitra.com/2016/11/Java-Cloning-Types-of-Cloning-Shallow-Deep-in-Details-with-Example.html"&gt;Java cloning&lt;/a&gt; in serialization, we have one marker interface Serializable which works like a flag for the JVM. Any class which implements &lt;code&gt;Serializable&lt;/code&gt; interface directly or through its parent can be serialised and classes which do not implement &lt;code&gt;Serializable&lt;/code&gt; can not be serialized.&lt;/p&gt;

&lt;p&gt;Java’s default serialization process is fully recursive, so whenever we try to serialize one object, the serialization process try to serialize all the fields (primitive and reference) with our class (except &lt;code&gt;static&lt;/code&gt; and &lt;code&gt;transient&lt;/code&gt; fields).  &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;When a class implements the&lt;code&gt;Serializable&lt;/code&gt; interface, all its sub-classes are serializable as well. But when an object has a reference to another object, these objects must implement the &lt;code&gt;Serializable&lt;/code&gt; interface separately. If our class is having even a single reference to a non &lt;code&gt;Serializable&lt;/code&gt; class then JVM will throw &lt;code&gt;NotSerializableException&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;
  
  
  Why Serializable is not implemented by Object?
&lt;/h2&gt;

&lt;p&gt;Now a question arises if Serialization is very basic functionality and any class which do not implement &lt;code&gt;Serializable&lt;/code&gt; can not be serialised, then why Serializable is not implemented by the &lt;code&gt;Object&lt;/code&gt; itself?, By this way, all our objects could be serialized by default.  &lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Object&lt;/code&gt; class does not implement &lt;code&gt;Serializable&lt;/code&gt; interface because we may not want to serialize all the objects e.g. serialising a thread does not make any sense because thread running in my JVM would be using my system's memory, persisting it and trying to run it in your JVM would make no sense.  &lt;/p&gt;
&lt;h2&gt;
  
  
  The transient and static fields do not get serialized
&lt;/h2&gt;

&lt;p&gt;If we want to serialize one object but do not want to serialize some specific fields then we can mark those fields as &lt;strong&gt;transient&lt;/strong&gt;.  &lt;/p&gt;

&lt;p&gt;All the &lt;strong&gt;static&lt;/strong&gt; fields belong to the class instead of the object, and the serialization process serialises the object so static fields can not be serialized.  &lt;/p&gt;

&lt;blockquote&gt;
&lt;ol&gt;
&lt;li&gt; Serialization does not care about access modifiers of the field such as &lt;code&gt;private&lt;/code&gt;. All non transient and non static fields are considered part of an object's persistent state and are eligible for serialisation.&lt;/li&gt;
&lt;li&gt; We can assign values to final fields in conscrutors only and serialization process do not invoke any constructor but still it can assign values to final fields.&lt;/li&gt;
&lt;/ol&gt;
&lt;/blockquote&gt;
&lt;h2&gt;
  
  
  What is serialVersionUID and Why should we declare it?
&lt;/h2&gt;

&lt;p&gt;Suppose we have a class and we have serialized its object to a file on the disk, and due to some new requirements, we added/removed one field from our class. Now if we try to deserialize the already serialized object we will get &lt;code&gt;InvalidClassException&lt;/code&gt;, why?  &lt;/p&gt;

&lt;p&gt;We get it because by default JVM associates a version number to each serializable class to control the class versioning. It is used to verify that the serialized and deserialized objects have the same attributes and thus are compatible with deserialization. The version number is maintained in a field called &lt;code&gt;serialVersionUID&lt;/code&gt;. If a serializable class doesn’t declare a &lt;code&gt;serialVersionUID&lt;/code&gt; JVM will generate one automatically at run-time.  &lt;/p&gt;

&lt;p&gt;If we change our class structure e.g. remove/add fields that version number also changes and according to JVM our class is not compatible with the class version of the serialized object. That's why we get the exception but if you really think about it, why should it be thrown just because I added a field? Couldn't the field just be set to its default value and then written out next time?  &lt;/p&gt;

&lt;p&gt;Yes, it can be done by providing the &lt;code&gt;serialVersionUID&lt;/code&gt; field manually and ensure it is always the same. It is highly recommended that each serializable class declares its &lt;code&gt;serialVersionUID&lt;/code&gt; as the generated one is compiler dependent and thus may result in unexpected &lt;em&gt;InvalidClassExceptions.&lt;/em&gt;  &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;You can use a utility that comes with the JDK distribution called &lt;code&gt;serialver&lt;/code&gt; to see what that code would be by default (it is just the hash code of the object by default).&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;
  
  
  Customizing Serialization and Deserialization with writeObject and readObject methods
&lt;/h2&gt;

&lt;p&gt;JVM has full control for serializing the object in the default serialization process but there are lots of downside of the using default serialization process, some of which are:  &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; It can not handle serialisation of fields which are not serializable.&lt;/li&gt;
&lt;li&gt; Deserialization process does not invoke constructors while creating the object so it can not call the initialization logic provided by the constructor.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;But we can override this the default serialization behaviour inside our Java class and provide some additional logic to enhance the normal process. This can be done by providing two methods &lt;code&gt;writeObject&lt;/code&gt; and &lt;code&gt;readObject&lt;/code&gt; inside the class that we want to serialize:  &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Custom serialization logic will allow us to have additional serialization logic on top of the default one e.g. encrypting object before serialization
private void writeObject(ObjectOutputStream oos) throws IOException {
  // Any Custom logic
 oos.defaultWriteObject(); // Calling the default serialization logic
  // Any Custom logic
}

// Custom deserialization logic will allow us to have additional deserialization logic on top of the default one e.g. decrypting object after deserialization
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
 // Any Custom logic
 ois.defaultReadObject(); // Calling the default deserialization logic
  // Any Custom logic
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Declaring both methods as private is necessary (public methods will not work) so rather than JVM nothing else can see them. This also proves that neither method is not inherited nor overridden or overloaded. JVM automatically checks these methods and call them during the serialization-deserialization process. JVM can call these private methods but other objects can not thus, the integrity of the class is maintained and the serialization protocol can continue to work as normal.  &lt;/p&gt;

&lt;p&gt;Even though those specialized private methods are provided, the object serialization works the same way by calling &lt;code&gt;ObjectOutputStream.writeObject()&lt;/code&gt; or &lt;code&gt;ObjectInputStream.readObject()&lt;/code&gt;.  &lt;/p&gt;

&lt;p&gt;The call to &lt;code&gt;ObjectOutputStream.writeObject()&lt;/code&gt; or &lt;code&gt;ObjectInputStream.readObject()&lt;/code&gt; kicks off the serialization protocol. First, the object is checked to ensure it implements &lt;code&gt;Serializable&lt;/code&gt; and then it is checked to see whether either of those private methods is provided. If they are provided, the stream class is passed as the parameter to these methods, giving the code control over its usage.  &lt;/p&gt;

&lt;p&gt;We can call &lt;code&gt;ObjectOutputStream.defaultWriteObject()&lt;/code&gt; and &lt;code&gt;ObjectInputStream.defaultReadObject()&lt;/code&gt; from these methods to gain default serialization logic. Those calls do what they sound like -- they perform the default writing and reading of the serialized object, which is important because we are not replacing the normal process, we are only adding to it.  &lt;/p&gt;

&lt;p&gt;Those private methods can be used for any customization you want to make in the serialization process, e.g. encryption can be added to the output and decryption to the input (note that the bytes are written and read in cleartext with no obfuscation at all). They could be used to add extra data to the stream, perhaps a company versioning code, the possibilities are truly limitless.  &lt;/p&gt;

&lt;p&gt;Apart from writeObject and readObject methods, we can also leverage other &lt;a href="https://www.programmingmitra.com/2019/08/java-serialization-magic-methods-and-their-uses-with-example.html"&gt;serialization magic methods&lt;/a&gt; to get some additional functionality.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Stopping Serialization and Deserialization
&lt;/h2&gt;

&lt;p&gt;Suppose we have a class which got the serialization capability from its parent, which means our class extends from another class which implements &lt;code&gt;Serializable&lt;/code&gt;.  &lt;/p&gt;

&lt;p&gt;It means anybody can serialize and deserialize the object of our class. But what if we do not want our class to be serialized or deserialized e.g. our class is a singleton and we want to prevent any new object creation, remember the &lt;a href="https://www.programmingmitra.com/2016/05/different-ways-to-create-objects-in-java-with-example.html"&gt;deserialization process creates a new object&lt;/a&gt;.  &lt;/p&gt;

&lt;p&gt;To stop the serialization for our class, we can once again use the above private methods to just throw the &lt;code&gt;NotSerializableException&lt;/code&gt;. Any attempt to serialize or deserialise our object will now always result in the exception being thrown. And since those methods are declared as &lt;code&gt;private&lt;/code&gt;, nobody can override your methods and change them.  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private void writeObject(ObjectOutputStream oos) throws IOException {
  throw new NotSerializableException("Serialization is not supported on this object!");
}

private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
  throw new NotSerializableException("Serialization is not supported on this object!");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;However, this is a violation of the Liskov Substitution Principle. And &lt;a href="https://www.programmingmitra.com/2019/08/java-serialization-magic-methods-and-their-uses-with-example.html"&gt;writeReplace and readResolve methods can be used&lt;/a&gt; to achieve singleton like behaviours. These methods are used to allow an object to provide an alternative representation for itself within an ObjectStream. In simple words, readResolve can be used to change the data that is deserialized through the readObject method and writeReplace can be used to change the data that is serialized through writeObject.&lt;/p&gt;

&lt;p&gt;Java &lt;a href="https://www.programmingmitra.com/2019/08/how-to-deep-clone-an-object-using-java-in-memory-serialization.html"&gt;serialization can also be used to deep clone an object&lt;/a&gt;. Java cloning is the most debatable topic in Java community and it surely does have its drawbacks but it is still the most popular and easy way of creating a copy of an object until that object is full filling mandatory conditions of Java cloning. I have covered cloning in details in a 3 article long &lt;a href="https://programmingmitra.blogspot.in/search/label/Java%20Cloning"&gt;Java Cloning Series&lt;/a&gt; which includes articles like &lt;a href="https://programmingmitra.blogspot.in/2016/11/Java-Cloning-Types-of-Cloning-Shallow-Deep-in-Details-with-Example.html"&gt;Java Cloning And Types Of Cloning (Shallow And Deep) In Details With Example&lt;/a&gt;, &lt;a href="https://programmingmitra.blogspot.in/2017/01/Java-cloning-copy-constructor-versus-Object-clone-or-cloning.html"&gt;Java Cloning - Copy Constructor Versus Cloning&lt;/a&gt;, &lt;a href="https://programmingmitra.blogspot.in/2017/01/java-cloning-why-copy-constructors-are-not-sufficient-or-good.html"&gt;Java Cloning - Even Copy Constructors Are Not Sufficient&lt;/a&gt;, go ahead and read them if you want to know more about cloning.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Serialization&lt;/strong&gt; is the process of saving an object's state to a sequence of bytes which then can be stored on a file or sent over the network and &lt;strong&gt;deserialization&lt;/strong&gt; is the process of reconstructing an object from those bytes.&lt;/li&gt;
&lt;li&gt; Only subclasses of the &lt;code&gt;Serializable&lt;/code&gt; interface can be serialized.&lt;/li&gt;
&lt;li&gt; If our class does not implement &lt;code&gt;Serializable&lt;/code&gt; interface or if it is having a reference to a non &lt;code&gt;Serializable&lt;/code&gt; class then JVM will throw &lt;code&gt;NotSerializableException&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; All &lt;code&gt;transient&lt;/code&gt; and &lt;code&gt;static&lt;/code&gt; fields do not get serialized.&lt;/li&gt;
&lt;li&gt; The &lt;code&gt;serialVersionUID&lt;/code&gt; is used to verify that the serialized and deserialized objects have the same attributes and thus are compatible with deserialization.&lt;/li&gt;
&lt;li&gt; We should create a &lt;code&gt;serialVersionUID&lt;/code&gt; field in our class so if we change our class structure (adding/removing fields) JVM will not through &lt;code&gt;InvalidClassException&lt;/code&gt;. If we do not provide it JVM provides one which might change when our class structure changes.&lt;/li&gt;
&lt;li&gt; We can override the default serialization behaviour inside our Java class by providing the implementation of &lt;code&gt;writeObject&lt;/code&gt; and &lt;code&gt;readObject&lt;/code&gt; methods.&lt;/li&gt;
&lt;li&gt; And we can call &lt;code&gt;ObjectOutputStream.defaultWriteObject()&lt;/code&gt; and &lt;code&gt;ObjectInputStream.defaultReadObject&lt;/code&gt; from &lt;code&gt;writeObject&lt;/code&gt; and &lt;code&gt;readObject&lt;/code&gt; methods to get the default serialization and deserialization logic.&lt;/li&gt;
&lt;li&gt; We can throw &lt;code&gt;NotSerializableException&lt;/code&gt; exception from &lt;code&gt;writeObject&lt;/code&gt; and &lt;code&gt;readObject&lt;/code&gt; , if we do not want our class to be serialized or deserialized.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Java Serialization process can be further customized and enhanced using the &lt;code&gt;Externalizable&lt;/code&gt; interface which I have explained in &lt;a href="https://www.programmingmitra.com/2019/08/how-to-customize-serialization-in-java-by-using-externalizable-interface.html"&gt;How to Customize Serialization In Java By Using Externalizable Interface&lt;/a&gt;.  &lt;/p&gt;

&lt;p&gt;I have also written a series of articles explaining item numbers 74 to 78 of Effective Java, which further discusses how Java serialization process can be enhanced, please go ahead and read them if you like.  &lt;/p&gt;

&lt;p&gt;You can find the complete source code for this article on this &lt;a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/SerializationExample.java"&gt;Github Repository&lt;/a&gt; and please feel free to provide your valuable feedback.&lt;/p&gt;

</description>
      <category>java</category>
      <category>serialization</category>
    </item>
    <item>
      <title>How to Customize Serialization In Java By Using Externalizable Interface</title>
      <dc:creator>Naresh Joshi</dc:creator>
      <pubDate>Wed, 28 Aug 2019 15:27:00 +0000</pubDate>
      <link>https://dev.to/njnareshjoshi/how-to-customize-serialization-in-java-by-using-externalizable-interface-3gja</link>
      <guid>https://dev.to/njnareshjoshi/how-to-customize-serialization-in-java-by-using-externalizable-interface-3gja</guid>
      <description>&lt;p&gt;In a previous article &lt;a href="https://www.programmingmitra.com/2019/08/what-is-serialization-everything-about-java-serialization-explained-with-example.html"&gt;Everything About Java Serialization Explained With Example&lt;/a&gt;, I explained how we can serialize/deserialize one object using &lt;code&gt;Serializable&lt;/code&gt; interface and also explain how we can &lt;a href="https://www.programmingmitra.com/2019/08/java-serialization-magic-methods-and-their-uses-with-example.html"&gt;customise the serialization process using writeObject and readObject methods&lt;/a&gt;.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Disadvantages Of Java Serialization Process
&lt;/h2&gt;

&lt;p&gt;But these customizations are not sufficient because JVM has full control of the serialization process and those customization logics are just additions to the default serialization process. We still have to use the default serialization logic by calling &lt;code&gt;ObjectOutputStream.defaultWriteObject()&lt;/code&gt; and &lt;code&gt;ObjectInputStream.defaultReadObject()&lt;/code&gt; from &lt;code&gt;writeObject&lt;/code&gt; and &lt;code&gt;readObject&lt;/code&gt; methods. And if do not call these default methods our object will not be serialized/deserialized.  &lt;/p&gt;

&lt;p&gt;The default serialization process is fully recursive. So whenever we try to serialize one object, the serialization process try to serialize all the fields (primitive and reference) with our class (except &lt;code&gt;static&lt;/code&gt; and &lt;code&gt;transient&lt;/code&gt; fields). Which makes serialization a very slow process.  &lt;/p&gt;

&lt;p&gt;Now let's assume we have an object with lots of fields which we do not want to serialize for some reasons (these fields will always be assigned with default values). With default serialization process we will have to make all these fields transient but it still will not be efficient because there will lot of checks to see if the fields are transient or not.  &lt;/p&gt;

&lt;p&gt;So as we can see there are lots of downside of the using default serialization process, like:  &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Customizations to serialization are not sufficient because JVM has full control of the serialization process and our customization logics are just additions to the default serialization process.&lt;/li&gt;
&lt;li&gt; Default serialization process is fully recursive and slow.&lt;/li&gt;
&lt;li&gt; In order to not to serialize a field, we have to declare it transient and lots of transient fields will again make the process slow.&lt;/li&gt;
&lt;li&gt; We can not control how our fields will be serialized and deserialized.&lt;/li&gt;
&lt;li&gt; Default serialization process does not invoke constructors while creating the object so it can not call the initialization logic provided by the constructor.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  What Is Externalization And Externalizable Interface
&lt;/h2&gt;

&lt;p&gt;As we saw above that the default java serialization is not efficient. We can solve some of these issues by using &lt;code&gt;Externalizable&lt;/code&gt; interface instead of &lt;code&gt;Serializable&lt;/code&gt; interface.  &lt;/p&gt;

&lt;p&gt;We can write your own serialization logic by implementing the &lt;a href="https://docs.oracle.com/javase/7/docs/api/java/io/Externalizable.html"&gt;Externalizable&lt;/a&gt; interface and overriding it’s methods &lt;code&gt;writeExternal()&lt;/code&gt; and &lt;code&gt;readExternal()&lt;/code&gt;. But with this approach, we will not get any kind of default serialization logic from JVM and it is up to us to provide the complete serialization and deserialization logic.  &lt;/p&gt;

&lt;p&gt;So it is very necessary to code the test these methods very carefully because it might break the serialization process. But the externalization process is very fast in comparison to the default serialization process if implemented properly.  &lt;/p&gt;

&lt;p&gt;We will use below &lt;code&gt;Employee&lt;/code&gt; class object as an example for the explanation:  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Using Externalizable, complete serialization/deserialization logic becomes our responsibility,
// We need to tell what to serialize using writeExternal() method and what to deserialize using readExternal(),
// We can even serialize/deserialize static and transient variables,
// With implementation of writeExternal() and readExternal(),  methods writeObject() and readObject() becomes redundant and they do not get called.
class Employee implements Externalizable {

   // This serialVersionUID field is necessary for Serializable as well as Externalizable to provide version control,
    // Compiler will provide this field if we do not provide it which might change if we modify class structure of our class, and we will get InvalidClassException,
    // If we provide a value to this field and do not change it, serialization-deserialization will not fail if we change our class structure.
    private static final long serialVersionUID = 2L;

    private String firstName;
    private transient String lastName; // Using Externalizable, we can even serialize/deserialize transient variables, so declaring fields transient becomes unnecessary.
    private int age;
    private static String department; // Using Externalizable, we can even serialize/deserialize static variables according to our need.


    // Mandatory to have to make our class Externalizable
    // When an Externalizable object is reconstructed, the object is created using public no-arg constructor before the readExternal method is called.
    // If a public no-arg constructor is not present then a InvalidClassException is thrown at runtime.
    public Employee() {
    }

    // All-arg constructor to create objects manually
    public Employee(String firstName, String lastName, int age, String department) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        Employee.department = department;

        validateAge();
    }

    private void validateAge() {
        System.out.println("Validating age.");

        if (age &amp;lt; 18 || age &amp;gt; 70) {
            throw new IllegalArgumentException("Not a valid age to create an employee");
        }
    }

    @Override
    // We need to tell what to serialize in writeExternal() method
    public void writeExternal(ObjectOutput out) throws IOException {
        System.out.println("Custom externalizable serialization logic invoked.");

        out.writeUTF(firstName);
        out.writeUTF(lastName);
        out.writeInt(age);
        out.writeUTF(department);
    }

    @Override
    // We need to tell what to deserialize in readExternal() method
    // The readExternal method must read the values in the same sequence and with the same types as were written by writeExternal
    public void readExternal(ObjectInput in) throws IOException {
        System.out.println("Custom externalizable serialization logic invoked.");

        firstName = in.readUTF();
        lastName = in.readUTF();
        age = in.readInt();
        department = in.readUTF();

        validateAge();
    }

    @Override
    public String toString() {
        return String.format("Employee {firstName='%s', lastName='%s', age='%s', department='%s'}", firstName, lastName, age, department);
    }

    // Custom serialization logic, It will be called only if we have implemented Serializable instead of Externalizable.
    private void writeObject(ObjectOutputStream oos) throws IOException {
        System.out.println("Custom serialization logic invoked.");
    }

    // Custom deserialization logic, It will be called only if we have implemented Serializable instead of Externalizable.
    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
        System.out.println("Custom deserialization logic invoked.");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  How Serialization works with Externalizable Interface
&lt;/h2&gt;

&lt;p&gt;As we can see above in our example &lt;code&gt;Employee&lt;/code&gt; class, we can write your own serialization logic by implementing the &lt;a href="https://docs.oracle.com/javase/7/docs/api/java/io/Externalizable.html"&gt;Externalizable&lt;/a&gt; interface and overriding its methods &lt;code&gt;writeExternal()&lt;/code&gt; and &lt;code&gt;readExternal()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The object can implement the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, and arrays.  &lt;/p&gt;

&lt;p&gt;The object can implement the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays. The readExternal method must read the values in the same sequence and with the same types as were written by writeExternal.  &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// We need to tell what fields to serialize in writeExternal() method
public void writeExternal(ObjectOutput out) throws IOException {
    System.out.println("Custom externalizable serialization logic invoked.");

    out.writeUTF(firstName);
    out.writeUTF(lastName);
    out.writeInt(age);
    out.writeUTF(department);
}

// We need to tell what fields to deserialize in readExternal() method
// The readExternal method must read the values in the same sequence and with the same types as were written by writeExternal
public void readExternal(ObjectInput in) throws IOException {
    System.out.println("Custom externalizable serialization logic invoked.");

    firstName = in.readUTF();
    lastName = in.readUTF();
    age = in.readInt();
    department = in.readUTF();

    validateAge();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;To serialize and deserialize our object to a file we need to follow the same procedure as we followed in the Serializable example which means calling &lt;code&gt;ObjectOutputStream.writeObject()&lt;/code&gt; and &lt;code&gt;ObjectInputStream.readObject()&lt;/code&gt; as done in the following code:  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ExternalizableExample {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Employee empObj = new Employee("Shanti", "Sharma", 25, "IT");
        System.out.println("Object before serialization  =&amp;gt; " + empObj.toString());

        // Serialization
        serialize(empObj);

        // Deserialization
        Employee deserializedEmpObj = deserialize();
        System.out.println("Object after deserialization =&amp;gt; " + deserializedEmpObj.toString());
    }

    // Serialization code
    static void serialize(Employee empObj) throws IOException {
        try (FileOutputStream fos = new FileOutputStream("data.obj");
             ObjectOutputStream oos = new ObjectOutputStream(fos))
        {
            oos.writeObject(empObj);
        }
    }

    // Deserialization code
    static Employee deserialize() throws IOException, ClassNotFoundException {
        try (FileInputStream fis = new FileInputStream("data.obj");
             ObjectInputStream ois = new ObjectInputStream(fis))
        {
            return (Employee) ois.readObject();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The &lt;code&gt;Externalizable&lt;/code&gt; interface is a child interface of &lt;code&gt;Serializable&lt;/code&gt; i.e. &lt;code&gt;Externalizable extends Serializable&lt;/code&gt;. So if we implement &lt;code&gt;Externalizable&lt;/code&gt; interface and override its &lt;code&gt;writeExternal()&lt;/code&gt; and &lt;code&gt;readExternal()&lt;/code&gt; methods then first preference is given to these methods over the default serialization mechanism provided by JVM. These methods supersede customized implementations of &lt;code&gt;writeObject&lt;/code&gt; and &lt;code&gt;readObject&lt;/code&gt; methods, So if we also provide &lt;code&gt;writeObject()&lt;/code&gt; and &lt;code&gt;readObject()&lt;/code&gt; then they will be ignored.  &lt;/p&gt;

&lt;p&gt;In the serialization process, each object to be serialized is tested for the Externalizable interface. If the object supports Externalizable, the writeExternal method is called. If the object does not support Externalizable and does implement Serializable, the object is saved using ObjectOutputStream.&lt;/p&gt;

&lt;p&gt;When an Externalizable object is reconstructed, an instance is created using the public no-arg constructor, then the readExternal method called. Serializable objects are restored by reading them from an ObjectInputStream.  &lt;/p&gt;

&lt;blockquote&gt;
&lt;ol&gt;
&lt;li&gt; When an Externizable object is reconstructed, and object is created using public no-arg constructor before the readExternal method is called. If a public no-arg constructor is not present then a InvalidClassException is thrown at runtime.&lt;/li&gt;
&lt;li&gt; Using Externalizable, we can even serialize/deserialize transient variables, so declaring fields transient becomes unnecessary.&lt;/li&gt;
&lt;li&gt; Using Externalizable, we can even serialize/deserialize static variables if we need to.&lt;/li&gt;
&lt;/ol&gt;
&lt;/blockquote&gt;

&lt;p&gt;An Externalizable instance can designate a substitution object via the writeReplace and readResolve methods documented in the Serializable interface.  &lt;/p&gt;

&lt;p&gt;Java &lt;a href="https://www.programmingmitra.com/2019/08/how-to-deep-clone-an-object-using-java-in-memory-serialization.html"&gt;serialization can also be used to deep clone an object&lt;/a&gt;. Java cloning is the most debatable topic in Java community and it surely does have its drawbacks but it is still the most popular and easy way of creating a copy of an object until that object is full filling mandatory conditions of Java cloning. I have covered cloning in details in a 3 article long &lt;a href="https://programmingmitra.blogspot.in/search/label/Java%20Cloning"&gt;Java Cloning Series&lt;/a&gt; which includes articles like &lt;a href="https://programmingmitra.blogspot.in/2016/11/Java-Cloning-Types-of-Cloning-Shallow-Deep-in-Details-with-Example.html"&gt;Java Cloning And Types Of Cloning (Shallow And Deep) In Details With Example&lt;/a&gt;, &lt;a href="https://programmingmitra.blogspot.in/2017/01/Java-cloning-copy-constructor-versus-Object-clone-or-cloning.html"&gt;Java Cloning - Copy Constructor Versus Cloning&lt;/a&gt;, &lt;a href="https://programmingmitra.blogspot.in/2017/01/java-cloning-why-copy-constructors-are-not-sufficient-or-good.html"&gt;Java Cloning - Even Copy Constructors Are Not Sufficient&lt;/a&gt;, go ahead and read them if you want to know more about cloning.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Differences between Externalizable vs Serializable
&lt;/h2&gt;

&lt;p&gt;Let’s list down the main differences between Externalizable and Serializable interfaces in java.  &lt;/p&gt;

&lt;p&gt;&lt;a href="////4.bp.blogspot.com/-Z-MlBmCNsYs/XVAcnBY5cNI/AAAAAAAAVwk/JkyAJ74GdgUTqSisG8LNbWDYoLJJO0pMQCK4BGAYYCw/s1600/Differences-between-Externalizable-vs-Serializable.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2zptnzuc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://4.bp.blogspot.com/-Z-MlBmCNsYs/XVAcnBY5cNI/AAAAAAAAVwk/JkyAJ74GdgUTqSisG8LNbWDYoLJJO0pMQCK4BGAYYCw/s640/Differences-between-Externalizable-vs-Serializable.png" alt=""&gt;&lt;/a&gt;  &lt;/p&gt;

&lt;p&gt;You can find the complete source code for this article on this &lt;a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/ExternalizableExample.java"&gt;Github Repository&lt;/a&gt; and please feel free to provide your valuable feedback.&lt;/p&gt;

</description>
      <category>java</category>
      <category>serialization</category>
      <category>externalizable</category>
    </item>
    <item>
      <title>How To Deep Clone An Object Using Java In Memory Serialization</title>
      <dc:creator>Naresh Joshi</dc:creator>
      <pubDate>Sat, 24 Aug 2019 09:38:14 +0000</pubDate>
      <link>https://dev.to/njnareshjoshi/how-to-deep-clone-an-object-using-java-in-memory-serialization-43a2</link>
      <guid>https://dev.to/njnareshjoshi/how-to-deep-clone-an-object-using-java-in-memory-serialization-43a2</guid>
      <description>&lt;p&gt;In my previous articles, I had explained the &lt;a href="https://www.programmingmitra.com/2016/11/Java-Cloning-Types-of-Cloning-Shallow-Deep-in-Details-with-Example.html" rel="noopener noreferrer"&gt;difference between deep and shallow cloning&lt;/a&gt; and &lt;a href="https://www.programmingmitra.com/2017/01/Java-cloning-copy-constructor-versus-Object-clone-or-cloning.html" rel="noopener noreferrer"&gt;how copy-constructors&lt;/a&gt; and &lt;a href="https://www.programmingmitra.com/2017/01/java-cloning-why-copy-constructors-are-not-sufficient-or-good.html" rel="noopener noreferrer"&gt;defensive copy methods&lt;/a&gt; are better than default java cloning.  &lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.programmingmitra.com/2016/11/Java-Cloning-Types-of-Cloning-Shallow-Deep-in-Details-with-Example.html" rel="noopener noreferrer"&gt;Java object cloning&lt;/a&gt; using &lt;a href="https://www.programmingmitra.com/2017/01/Java-cloning-copy-constructor-versus-Object-clone-or-cloning.html" rel="noopener noreferrer"&gt;copy constructors&lt;/a&gt; and &lt;a href="https://www.programmingmitra.com/2017/01/java-cloning-why-copy-constructors-are-not-sufficient-or-good.html" rel="noopener noreferrer"&gt;defensive copy methods&lt;/a&gt; certainly have some advantages but we have to explicitly write some code to achieve deep cloning in all these approaches. And still, there are chances that we might miss something and do not get deeply cloned object.  &lt;/p&gt;

&lt;p&gt;And as discussed in &lt;a href="https://www.programmingmitra.com/2016/05/different-ways-to-create-objects-in-java-with-example.html" rel="noopener noreferrer"&gt;5 different ways to create objects in java&lt;/a&gt;, deserialising a serialised object creates a new object with the same state as in the serialized object. So similar to above cloning approaches we can achieve deep cloning functionality using object &lt;a href="https://www.programmingmitra.com/2019/08/what-is-serialization-everything-about-java-serialization-explained-with-example.html" rel="noopener noreferrer"&gt;serialization and deserialization&lt;/a&gt; as well and with this approach we do not have worry about or write code for deep cloning, we get it by default.  &lt;/p&gt;

&lt;p&gt;However, cloning an object using serialization comes with some performance overhead and we can improve on it by using &lt;strong&gt;in-memory serialization&lt;/strong&gt; if we just need to clone the object and don’t need to persist it in a file for future use.&lt;/p&gt;

&lt;p&gt;We will use below &lt;code&gt;Employee&lt;/code&gt; class as an example which has &lt;code&gt;name&lt;/code&gt;, &lt;code&gt;doj&lt;/code&gt; and &lt;code&gt;skills&lt;/code&gt; as the state, for deep cloning we do not need to worry about the code&amp;gt;name field because it is a String object and by default all &lt;a href="https://www.programmingmitra.com/2018/02/why-string-is-immutable-and-final-in-java.html" rel="noopener noreferrer"&gt;strings are immutable in nature&lt;/a&gt;.  &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;You can read more about immutability on &lt;a href="https://www.programmingmitra.com/2018/02/how-to-create-immutable-class-in-java.html" rel="noopener noreferrer"&gt;How to Create an Immutable Class in Java&lt;/a&gt; and &lt;a href="https://www.programmingmitra.com/2018/02/why-string-is-immutable-and-final-in-java.html" rel="noopener noreferrer"&gt;Why String is Immutable and Final&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Employee implements Serializable {
    private static final long serialVersionUID = 2L;

    private String name;
    private LocalDate doj;
    private List&amp;lt;String&amp;gt; skills;

    public Employee(String name, LocalDate doj, List&amp;lt;String&amp;gt; skills) {
        this.name = name;
        this.doj = doj;
        this.skills = skills;
    }

    public String getName() { return name; }
    public LocalDate getDoj() { return doj; }
    public List&amp;lt;String&amp;gt; getSkills() { return skills; }

    // Method to deep clone a object using in memory serialization
    public Employee deepClone() throws IOException, ClassNotFoundException {
        // First serializing the object and its state to memory using ByteArrayOutputStream instead of FileOutputStream.
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bos);
        out.writeObject(this);

        // And then deserializing it from memory using ByteArrayOutputStream instead of FileInputStream.
        // Deserialization process will create a new object with the same state as in the serialized object,
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream in = new ObjectInputStream(bis);
        return (Employee) in.readObject();
    }

    @Override
    public String toString() {
        return String.format("Employee{name='%s', doj=%s, skills=%s}", name, doj, skills);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Employee employee = (Employee) o;

        return Objects.equals(name, employee.name) &amp;amp;&amp;amp;
            Objects.equals(doj, employee.doj) &amp;amp;&amp;amp;
            Objects.equals(skills, employee.skills);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, doj, skills);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;To deep clone an object of &lt;code&gt;Employee&lt;/code&gt; class I have provided a &lt;code&gt;deepClone()&lt;/code&gt; method which serializes the object to memory by using &lt;code&gt;ByteArrayOutputStream&lt;/code&gt; instead of the &lt;code&gt;FileOutputStream&lt;/code&gt; and deserialises it back using &lt;code&gt;ByteArrayInputStream&lt;/code&gt; instead of the &lt;code&gt;FileInputStream&lt;/code&gt;. Here we are serializing the object into bytes and deserializing it from bytes to object again.  &lt;/p&gt;

&lt;p&gt;&lt;a href="https://1.bp.blogspot.com/-mVY5K1h2smA/XVj7JdqZxGI/AAAAAAAAVzI/rCOaiHV5znMf1KmTgLdmySVTV8amaPEKACLcBGAs/s1600/Java-Deep-Cloning-Using-Serialization.png" rel="noopener noreferrer"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2F1.bp.blogspot.com%2F-mVY5K1h2smA%2FXVj7JdqZxGI%2FAAAAAAAAVzI%2FrCOaiHV5znMf1KmTgLdmySVTV8amaPEKACLcBGAs%2Fs1600%2FJava-Deep-Cloning-Using-Serialization.png" title="How To Deep Clone An Object Using Java In Memory Serialization" alt="How To Deep Clone An Object Using Java In Memory Serialization"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Employee class implements &lt;code&gt;Serializable&lt;/code&gt; interface to achieve serialization which has its own disadvantages and we can overcome some of these disadvantages by &lt;a href="https://www.programmingmitra.com/2019/08/how-to-customize-serialization-in-java-by-using-externalizable-interface.html" rel="noopener noreferrer"&gt;customizing the serialization process by using Externalizable interface&lt;/a&gt;.  &lt;/p&gt;

&lt;p&gt;We can run below tests to see if our cloning approach is deep or just shallow, here all &lt;code&gt;==&lt;/code&gt; operations will return false (because both objects are separate) and all &lt;code&gt;equals&lt;/code&gt; will return true (because both have the same content).  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static void main(String[] args) throws IOException, ClassNotFoundException {
 Employee emp = new Employee("Naresh Joshi", LocalDate.now(), Arrays.asList("Java", "Scala", "Spring"));
 System.out.println("Employee object: " + emp);

 // Deep cloning `emp` object by using our `deepClone` method.
 Employee clonedEmp = emp.deepClone();
 System.out.println("Cloned employee object: " + clonedEmp);

 System.out.println();

 // All of this will print false because both objects are separate.
 System.out.println(emp == clonedEmp);
 System.out.println(emp.getDoj() == clonedEmp.getDoj());
 System.out.println(emp.getSkills() == clonedEmp.getSkills());

 System.out.println();

 // All of this will print true because `clonedEmp` is a deep clone of `emp` and both have the same content.
 System.out.println(Objects.equals(emp, clonedEmp));
 System.out.println(Objects.equals(emp.getDoj(), clonedEmp.getDoj()));
 System.out.println(Objects.equals(emp.getSkills(), clonedEmp.getSkills()));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We know deserialization process creates a new object every time which is not good if we have to make our class singleton. And that's why we need to override and disable serialization for our singleton class which we can achieve by providing writeReplace and readResolve methods.  &lt;/p&gt;

&lt;p&gt;Similar to serialization, Java cloning also does not play along with singleton pattern, and that's why we need to override and disable it as well. We can do that by implementinng cloning in way so that it will either throw &lt;code&gt;CloneNotSupportedException&lt;/code&gt; or return the same instance everytime.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;You can read more about Java cloning and serialization on &lt;a href="https://www.programmingmitra.com/search/label/Java%20Cloning" rel="noopener noreferrer"&gt;Java Cloning&lt;/a&gt; and &lt;a href="https://www.programmingmitra.com/search/label/Serialization" rel="noopener noreferrer"&gt;Java Serialization&lt;/a&gt; topics.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You can find the complete source code for this article on this &lt;a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/DeepCloningUsingSerializationExample.java" rel="noopener noreferrer"&gt;Github Repository&lt;/a&gt; and please feel free to provide your valuable feedback.&lt;/p&gt;

</description>
      <category>java</category>
      <category>serialization</category>
      <category>cloning</category>
    </item>
    <item>
      <title>Why We Should Follow Method Overriding Rules</title>
      <dc:creator>Naresh Joshi</dc:creator>
      <pubDate>Mon, 01 Jul 2019 15:29:39 +0000</pubDate>
      <link>https://dev.to/njnareshjoshi/why-we-should-follow-method-overriding-rules-31lo</link>
      <guid>https://dev.to/njnareshjoshi/why-we-should-follow-method-overriding-rules-31lo</guid>
      <description>&lt;p&gt;In my previous articles &lt;a href="https://programmingmitra.com/2017/12/why-to-follow-method-overloading-rules.html"&gt;Why Should We Follow Method Overloading Rules&lt;/a&gt;, I discussed method overloading and rules we need to follow to overload a method. I have also discussed why we need to follow these rules and why some method overloading rules are necessary and others are optional.  &lt;/p&gt;

&lt;p&gt;In a similar manner in this article, we will see what rules we need to follow to override a method and why we should follow these rules.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Method Overriding and its Rules
&lt;/h2&gt;

&lt;p&gt;As discussed in &lt;a href="https://programmingmitra.com/2017/05/everything-about-method-overloading-vs-method-overriding.html"&gt;Everything About Method Overloading Vs Method Overriding&lt;/a&gt;, every child class inherits all the inheritable behaviour from its parent class but the child class can also define its own new behaviours or override some of the inherited behaviours.  &lt;/p&gt;

&lt;p&gt;Overriding means redefining a behaviour (method) again in the child class which was already defined by its parent class but to do so overriding method in the child class must follow certain rules and guidelines.  &lt;/p&gt;

&lt;p&gt;With respect to the method it overrides, the overriding method must follow the following rules.&lt;br&gt;&lt;br&gt;
&lt;a href="////3.bp.blogspot.com/-hhpGgaXYUgg/WjqobOrC3PI/AAAAAAAAMr8/HMu27uIEnLg9MkvYSGfxYy_8mjc0ZEq8QCK4BGAYYCw/s1600/method-overriding-rules.JPG"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--e80pc90O--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://3.bp.blogspot.com/-hhpGgaXYUgg/WjqobOrC3PI/AAAAAAAAMr8/HMu27uIEnLg9MkvYSGfxYy_8mjc0ZEq8QCK4BGAYYCw/s1600/method-overriding-rules.JPG" alt="Why We Should Follow Method Overriding Rules" title="Why We Should Follow Method Overriding Rules"&gt;&lt;/a&gt;  &lt;/p&gt;

&lt;p&gt;To understand these reasons properly let's consider below example where we have a class &lt;code&gt;Mammal&lt;/code&gt; which defines &lt;code&gt;readAndGet&lt;/code&gt; method which is reading some file and returning an instance of class &lt;code&gt;Mammal&lt;/code&gt;.  &lt;/p&gt;

&lt;p&gt;Class &lt;code&gt;Human&lt;/code&gt; extends class &lt;code&gt;Mammal&lt;/code&gt; and overrides &lt;code&gt;readAndGet&lt;/code&gt; method to return the instance of &lt;code&gt;Human&lt;/code&gt; instead of an instance of &lt;code&gt;Mammal&lt;/code&gt;.  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Mammal {
    public Mammal readAndGet() throws IOException {//read file and return Mammal`s object}
}

class Human extends Mammal {
    @Override
    public Human readAndGet() throws FileNotFoundException {//read file and return Human object}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And we know in case of method overriding we can make polymorphic calls. Which means if we assign a child instance to a parent reference and call an overridden method on that reference eventually the method from child class will get called. Let's do that  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Mammal mammal = new Human();
try {
    Mammal obj = mammal.readAndGet();
} catch (IOException ex) {..}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As discussed in  &lt;a href="https://programmingmitra.com/2017/05/how-does-jvm-handle-method-overriding-internally.html"&gt;How Does JVM Handle Method Overloading and Overriding Internally&lt;/a&gt; till compilation phase compiler thinks the method is getting called from the parent class. While bytecode generation phase compiler generates a &lt;code&gt;constant pool&lt;/code&gt; where it maps every method string literal and class reference to a memory reference  &lt;/p&gt;

&lt;p&gt;During runtime, JVM creates a &lt;code&gt;vtable&lt;/code&gt; or &lt;code&gt;virtual table&lt;/code&gt; to identify which method is getting called exactly. JVM creates a &lt;code&gt;vtable&lt;/code&gt; for every class and it is common for all the objects of that class. Mammal row in a &lt;code&gt;vtable&lt;/code&gt; contains method name and memory reference of that method.  &lt;/p&gt;

&lt;p&gt;First JVM creates a &lt;code&gt;vtable&lt;/code&gt; for the parent class and then copy that parent's &lt;code&gt;vtable&lt;/code&gt; to child class's &lt;code&gt;vtable&lt;/code&gt; and update just the memory reference for the overloaded method while keeping the same method name.  &lt;/p&gt;

&lt;p&gt;You can read it more clearly on  &lt;a href="https://programmingmitra.com/2017/05/how-does-jvm-handle-method-overriding-internally.html"&gt;How Does JVM Handle Method Overloading and Overriding Internally&lt;/a&gt; if it seems hard. So as of now, we are clear that  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  For compiler &lt;code&gt;mammal.readAndGet()&lt;/code&gt; means method is getting called from instance of class &lt;code&gt;Mammal&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  For JVM &lt;code&gt;mammal.readAndGet()&lt;/code&gt; is getting called from a memory address which &lt;code&gt;vtable&lt;/code&gt; is holding for &lt;code&gt;Mammal.readAndGet()&lt;/code&gt; which is pointing to a method call from class &lt;code&gt;Human&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Why overriding method must have the same name and same argument list
&lt;/h2&gt;

&lt;p&gt;Well conceptually &lt;code&gt;mammal&lt;/code&gt; is pointing to an object of class &lt;code&gt;Human&lt;/code&gt; and we are calling &lt;code&gt;readAndGet&lt;/code&gt; method on &lt;code&gt;mammal&lt;/code&gt;, so to get this call resolved at runtime &lt;code&gt;Human&lt;/code&gt; should also have a method &lt;code&gt;readAndGet&lt;/code&gt;. And if &lt;code&gt;Human&lt;/code&gt; has inherited that method from &lt;code&gt;Mammal&lt;/code&gt; then there is no problem but if &lt;code&gt;Human&lt;/code&gt; is overriding &lt;code&gt;readAndGet&lt;/code&gt;, it should provide the same method signature as provided by &lt;code&gt;Mammal&lt;/code&gt; because the method has been already got called according to that method signature.  &lt;/p&gt;

&lt;p&gt;But you may be asking how it is handled physically from &lt;code&gt;vtables&lt;/code&gt; so I must tell you that, JVM creates a &lt;code&gt;vtable&lt;/code&gt; for every class and when it encounters an overriding method it keeps the same method name (&lt;code&gt;Mammal.readAndGet()&lt;/code&gt;) while just update the memory address for that method. So both overridden and overriding method must have the same method and argument list.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Why overriding method must have the same or covariant return type
&lt;/h2&gt;

&lt;p&gt;So we know, for compiler the method is getting called from class &lt;code&gt;Mammal&lt;/code&gt; and for JVM call is from the instance of class &lt;code&gt;Human&lt;/code&gt; but in both cases, &lt;code&gt;readAndGet&lt;/code&gt; method call must return an object which can be assigned to &lt;code&gt;obj&lt;/code&gt;. And since &lt;code&gt;obj&lt;/code&gt; is of the type &lt;code&gt;Mammal&lt;/code&gt; it can either hold an instance of &lt;code&gt;Mammal&lt;/code&gt; class or an instance of a child class of &lt;code&gt;Mammal&lt;/code&gt; (child of &lt;code&gt;Mammal&lt;/code&gt; are covariant to &lt;code&gt;Mammal&lt;/code&gt;).  &lt;/p&gt;

&lt;p&gt;Now suppose if &lt;code&gt;readAndGet&lt;/code&gt; method in &lt;code&gt;Human&lt;/code&gt; class is returning something else so during compile time &lt;code&gt;mammal.readAndGet()&lt;/code&gt; will not create any problem but at runtime, this will cause a &lt;code&gt;ClassCastException&lt;/code&gt; because at runtime &lt;code&gt;mammal.readAndGet()&lt;/code&gt; will get resolved to &lt;code&gt;new Human().readAndGet()&lt;/code&gt; and this call will not return an object of type &lt;code&gt;Mammal&lt;/code&gt;.  &lt;/p&gt;

&lt;p&gt;And this why having a different return type is not allowed by the compiler in the first place.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Why overriding method must not have a more restrictive access modifier
&lt;/h2&gt;

&lt;p&gt;The same logic is applicable here as well, call to &lt;code&gt;readAndGet&lt;/code&gt; method will be resolved at runtime and as we can see &lt;code&gt;readAndGet&lt;/code&gt; is public in class &lt;code&gt;Mammal&lt;/code&gt;, now suppose  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  If we define &lt;code&gt;readAndGet&lt;/code&gt; as &lt;code&gt;default&lt;/code&gt; or &lt;code&gt;protected&lt;/code&gt; in &lt;code&gt;Human&lt;/code&gt; but Human is defined in another package&lt;/li&gt;
&lt;li&gt;  If we define &lt;code&gt;readAndGet&lt;/code&gt; as &lt;code&gt;private&lt;/code&gt; in &lt;code&gt;Human&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In both cases, the code will compile successfully because for compiler &lt;code&gt;readAndGet&lt;/code&gt; is getting called from class &lt;code&gt;Mammal&lt;/code&gt; but in both cases, JVM will not be able to access &lt;code&gt;readAndGet&lt;/code&gt; from &lt;code&gt;Human&lt;/code&gt; because it will be restricted.  &lt;/p&gt;

&lt;p&gt;So to avoid this uncertainty, assigning restrictive access to the overriding method in the child class is not allowed at all.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Why overriding method may have less restrictive access modifier
&lt;/h2&gt;

&lt;p&gt;If &lt;code&gt;readAndGet&lt;/code&gt; method is accessible from &lt;code&gt;Mammal&lt;/code&gt; and we are able to execute &lt;code&gt;mammal.readAndGet()&lt;/code&gt; which means this method is accessible. And we make &lt;code&gt;readAndGet&lt;/code&gt; less restrictive &lt;code&gt;Human&lt;/code&gt; which means it will be more open to getting called.  &lt;/p&gt;

&lt;p&gt;So making the overriding method less restrictive cannot create any problem in the future and that's it is allowed.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Why overriding method must not throw new or broader checked exceptions
&lt;/h2&gt;

&lt;p&gt;Because &lt;code&gt;IOException&lt;/code&gt; is a checked exception compiler will force us to catch it whenever we call &lt;code&gt;readAndGet&lt;/code&gt; on &lt;code&gt;mammal&lt;/code&gt;  &lt;/p&gt;

&lt;p&gt;Now suppose &lt;code&gt;readAndGet&lt;/code&gt; in &lt;code&gt;Human&lt;/code&gt; is throwing any other checked exception e.g. &lt;code&gt;Exception&lt;/code&gt; and we know &lt;code&gt;readAndGet&lt;/code&gt; will get called from the instance of &lt;code&gt;Human&lt;/code&gt; because &lt;code&gt;mammal&lt;/code&gt; is holding &lt;code&gt;new Human()&lt;/code&gt;.  &lt;/p&gt;

&lt;p&gt;Because for compiler the method is getting called from &lt;code&gt;Mammal&lt;/code&gt;, so the compiler will force us to handle only &lt;code&gt;IOException&lt;/code&gt; but at runtime we know method will be throwing &lt;code&gt;Exception&lt;/code&gt; which is not getting handled and our code will break if the method throws an exception.  &lt;/p&gt;

&lt;p&gt;That's why it is prevented at the compiler level itself and we are not allowed to throw any new or broader checked exception because it will not be handled by JVM at the end.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Why overriding method may throw narrower checked exceptions or any unchecked exception
&lt;/h2&gt;

&lt;p&gt;But if &lt;code&gt;readAndGet&lt;/code&gt; in &lt;code&gt;Human&lt;/code&gt; throws any sub-exception of &lt;code&gt;IOException&lt;/code&gt; e.g., &lt;code&gt;FileNotFoundException&lt;/code&gt;, it will be handled because &lt;code&gt;catch (IOException ex)&lt;/code&gt; can handle all child of &lt;code&gt;IOException&lt;/code&gt;.  &lt;/p&gt;

&lt;p&gt;And we know unchecked exception (subclasses of &lt;code&gt;RuntimeException&lt;/code&gt;) are called unchecked because we don't need to handle them necessarily.&lt;/p&gt;

&lt;p&gt;And that's why overriding methods are allowed to throw narrower checked and other unchecked exceptions.  &lt;/p&gt;

&lt;p&gt;To force our code to adhere method overriding rules we should always use &lt;code&gt;@Override&lt;/code&gt; annotation on our overriding methods, &lt;code&gt;@Override&lt;/code&gt; annotation force compiler to check if the method is a valid override or not.  &lt;/p&gt;

&lt;p&gt;You can find the complete code on this &lt;a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/OverridingInternalExample.java"&gt;Github Repository&lt;/a&gt; and please feel free to provide your valuable feedback.&lt;/p&gt;

</description>
      <category>java</category>
      <category>polymorphism</category>
    </item>
    <item>
      <title>Why Instance Variable Of Super Class Is Not Overridden In Sub Class</title>
      <dc:creator>Naresh Joshi</dc:creator>
      <pubDate>Sun, 30 Jun 2019 08:38:09 +0000</pubDate>
      <link>https://dev.to/njnareshjoshi/why-instance-variable-of-super-class-is-not-overridden-in-sub-class-105c</link>
      <guid>https://dev.to/njnareshjoshi/why-instance-variable-of-super-class-is-not-overridden-in-sub-class-105c</guid>
      <description>&lt;p&gt;When we create a variable in both parent and child class with the same name, and try to access it using parent's class reference which is holding a child class's object then what do we get?  &lt;/p&gt;

&lt;p&gt;In order to understand this, let us consider below example where we declare a variable &lt;code&gt;x&lt;/code&gt; with the same name in both &lt;code&gt;Parent&lt;/code&gt; and &lt;code&gt;Child&lt;/code&gt; classes.  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Parent {
    // Declaring instance variable by name `x`
    String x = "Parent`s Instance Variable";

    public void print() {
        System.out.println(x);
    }
}

class Child extends Parent {

    // Hiding Parent class's variable `x` by defining a variable in the child class with the same name.
    String x = "Child`s Instance Variable";

    @Override
    public void print() {
        System.out.print(x);

        // If we still want to access variable from super class, we do that by using `super.x`
        System.out.print(", " + super.x + "\n");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And now if we try to access &lt;code&gt;x&lt;/code&gt; using below code, what &lt;code&gt;System.out.println(parent.x)&lt;/code&gt; will print  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Parent parent = new Child();
System.out.println(parent.x) // Output -- Parent`s Instance Variable
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Well generally, we will say &lt;code&gt;Child&lt;/code&gt; class will override the variable declared in the &lt;code&gt;Parent&lt;/code&gt; class and &lt;code&gt;parent.x&lt;/code&gt; will give us whatever &lt;code&gt;Child's&lt;/code&gt; object is holding. Because it is the same thing which happens while we do the same kind of operation on methods.  &lt;/p&gt;

&lt;p&gt;But actually it is not, and &lt;code&gt;parent.x&lt;/code&gt; will give us value Parent`s Instance Variable which is declared in &lt;code&gt;Parent&lt;/code&gt; class but why?&lt;/p&gt;

&lt;p&gt;Because variables in Java do not follow polymorphism and overriding is only applicable to methods but not to variables. And when an instance variable in a child class has the same name as an instance variable in a parent class, then the instance variable is chosen from the reference type.  &lt;/p&gt;

&lt;p&gt;In Java, when we define a variable in Child class with a name which we have already used to define a variable in the Parent class, Child class's variable hides parent's variable, even if their types are different. And this concept is known as &lt;strong&gt;Variable Hiding.&lt;/strong&gt;  &lt;/p&gt;

&lt;p&gt;In other words, when the child and parent class both have a variable with the same name, Child class's variable hides the parent class's variable. You can read more on variable hiding in the article &lt;a href="https://programmingmitra.com/2018/02/what-is-variable-shadowing-and-hiding.html"&gt;What is Variable Shadowing and Hiding in Java&lt;/a&gt;.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Variable Hiding is not the same as Method Overriding
&lt;/h2&gt;

&lt;p&gt;While variable hiding looks like overriding a variable similar to method overriding but it is not, overriding is applicable only to methods while hiding is applicable to variables.  &lt;/p&gt;

&lt;p&gt;In the case of &lt;strong&gt;method overriding&lt;/strong&gt;, overriding methods completely replaces the inherited methods so when we try to access the method from parent's reference by holding child's object, the method from child class gets called. You can read more about overriding and how overridden methods completely replace the inherited methods on &lt;a href="https://programmingmitra.com/2017/05/everything-about-method-overloading-vs-method-overriding.html"&gt;Everything About Method Overloading Vs Method Overriding&lt;/a&gt;, &lt;a href="https://programmingmitra.com/2017/12/why-we-should-follow-method-overriding-rules.html"&gt;Why We Should Follow Method Overriding Rules&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;But in &lt;strong&gt;variable hiding&lt;/strong&gt; child class hides the inherited variables instead of replacing which basically means is that the object of Child class contains both variables but Child's variable hides Parent's variable. so when we try to access the variable from within Child class, it will be accessed from the child class.  &lt;/p&gt;

&lt;p&gt;And if I simplify section &lt;a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#d5e10238"&gt;Example 8.3.1.1-3. Hiding of Instance Variables&lt;/a&gt; of &lt;a href="http://docs.oracle.com/javase/specs/jls/se7/html/index.html"&gt;Java language specification&lt;/a&gt;:  &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;When we declare a variable in a &lt;code&gt;Child&lt;/code&gt; class which has the same name e.g. &lt;code&gt;x&lt;/code&gt; as an instance variable in a &lt;code&gt;Parent&lt;/code&gt; class then  &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Child class's object contains both variables (one inherited from &lt;code&gt;Parent&lt;/code&gt; class and other declared in &lt;code&gt;Child&lt;/code&gt; itself) but the child class variable hides the parent class's variable.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Because the declaration of &lt;code&gt;x&lt;/code&gt; in class &lt;code&gt;Child&lt;/code&gt; hides the definition of &lt;code&gt;x&lt;/code&gt; in class &lt;code&gt;Parent&lt;/code&gt;, within the declaration of class &lt;code&gt;Child&lt;/code&gt;, the simple name &lt;code&gt;x&lt;/code&gt; always refers to the field declared within class &lt;code&gt;Child&lt;/code&gt;. And if the code in methods of &lt;code&gt;Child&lt;/code&gt; class wants to refer to the variable &lt;code&gt;x&lt;/code&gt; of &lt;code&gt;Parent&lt;/code&gt; class then this can be done as &lt;code&gt;super.x&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If we are trying to access the variable outside of &lt;code&gt;Parent&lt;/code&gt; and &lt;code&gt;Child&lt;/code&gt; class, then the instance variable is chosen from the reference type. Thus, the expression &lt;code&gt;parent2.x&lt;/code&gt; in the following code gives the variable value which belongs to parent class even if it is holding the object of the &lt;code&gt;Child&lt;/code&gt; but &lt;code&gt;((Child) parent2).x&lt;/code&gt; accesses the value from the &lt;code&gt;Child&lt;/code&gt; class because we cast the same reference to &lt;code&gt;Child&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="////2.bp.blogspot.com/-ri37eZ4bbVk/W-WFc9in3sI/AAAAAAAAR9I/brSieunxW483qLpJU9dWPVo-q5SuBsupQCK4BGAYYCw/s1600/variable-shadowing.jpeg"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zzx1gldk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://2.bp.blogspot.com/-ri37eZ4bbVk/W-WFc9in3sI/AAAAAAAAR9I/brSieunxW483qLpJU9dWPVo-q5SuBsupQCK4BGAYYCw/s1600/variable-shadowing.jpeg" alt="Why Instance Variable Of Super Class Is Not Overridden In Sub Class due to variable shadowing" title="Why Instance Variable Of Super Class Is Not Overridden In Sub Class due to variable shadowing"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Variable Hiding Is Designed This Way
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;So we know that instance variables are chosen from the reference type, not instance type, and polymorphism is not applicable to variables&lt;/strong&gt; but the real question is why? why variables are designed to follow hiding instead of overriding.  &lt;/p&gt;

&lt;p&gt;Because variable overriding might break methods inherited from the parent if we change its type in the child class.&lt;/p&gt;

&lt;p&gt;We know every child class inherits variables and methods (state and behaviour) from its parent class. Imagine if Java allows variable overriding and we change the type of a variable from &lt;code&gt;int&lt;/code&gt; to &lt;code&gt;Object&lt;/code&gt; in the child class. It will break any method which is using that variable and because the child has inherited those methods from the parent, the compiler will give errors in &lt;code&gt;child&lt;/code&gt; class.  &lt;/p&gt;

&lt;p&gt;For example:  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Parent {
    int x;
    public int increment() {
        return ++x;
    }
    public int getX() {
        return x;
    }
}

class Child extends Parent {
    Object x;
    // Child is inherting increment(), getX() from Parent and both methods returns an int 
    // But in child class type of x is Object, so increment(), getX() will fail to compile. 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If &lt;code&gt;Child.x&lt;/code&gt; overrides &lt;code&gt;Parent.x&lt;/code&gt;, how can &lt;code&gt;increment()&lt;/code&gt; and &lt;code&gt;getX()&lt;/code&gt; work? In the subclass, these methods will try to return the value of a field of the wrong type!  &lt;/p&gt;

&lt;p&gt;And as mentioned, if Java allows variable overriding then Child's variable cannot substitute Parent's variable and this would break the Liskov Substitutability Principle (LSP).  &lt;/p&gt;

&lt;h2&gt;
  
  
  Why Instance Variable Is Chosen from Reference Type Instead Of Instance
&lt;/h2&gt;

&lt;p&gt;As explained in &lt;a href="https://programmingmitra.com/2017/05/how-does-jvm-handle-method-overriding-internally.html"&gt;How Does JVM Handle Method Overloading and Overriding Internally&lt;/a&gt;,  at compile time overriding method calls are treated from the reference class only but all overridden methods get replaced by the overriding method at the runtime using a vtable and this phenomenon is called runtime polymorphism.&lt;/p&gt;

&lt;p&gt;Similarly, at compile time variable access is also treated from the reference type but as we discussed variables do not follow overriding or runtime polymorphism, so they are not replaced by child class variables at the runtime and still refer to the reference type.&lt;/p&gt;

&lt;p&gt;Generally speaking, nobody will ever recommend hiding fields as it makes code difficult to read and creates confusion. This kind of confusion will not there if we always stick to &lt;a href="https://programmingmitra.com/2016/05/plain-old-java-object-pojo-explained.html"&gt;General Guidelines to create POJOs&lt;/a&gt; and encapsulate our fields by declaring them as private and provides getters/setters as required so the variables are not visible outside that class and child class cannot access them.  &lt;/p&gt;

&lt;p&gt;You can find the complete code on this &lt;a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/VariableShadowingExample.java"&gt;Github Repository&lt;/a&gt; and please feel free to provide your valuable feedback.&lt;/p&gt;

</description>
      <category>java</category>
      <category>polymorphism</category>
    </item>
    <item>
      <title>Java Cloning - Why Even Copy Constructors Are Not Sufficient</title>
      <dc:creator>Naresh Joshi</dc:creator>
      <pubDate>Mon, 24 Jun 2019 16:13:10 +0000</pubDate>
      <link>https://dev.to/njnareshjoshi/java-cloning-why-even-copy-constructors-are-not-sufficient-mlo</link>
      <guid>https://dev.to/njnareshjoshi/java-cloning-why-even-copy-constructors-are-not-sufficient-mlo</guid>
      <description>&lt;p&gt;This is third article in &lt;a href="https://programmingmitra.blogspot.in/search/label/Java%20Cloning?max-results=6"&gt;Java Cloning&lt;/a&gt; series, In previous two articles &lt;a href="https://programmingmitra.blogspot.in/2016/11/Java-Cloning-Types-of-Cloning-Shallow-Deep-in-Details-with-Example.html"&gt;Java Cloning and Types of Cloning (Shallow and Deep) in Details&lt;/a&gt; and &lt;a href="https://programmingmitra.blogspot.in/2017/01/Java-cloning-copy-constructor-versus-Object-clone-or-cloning.html"&gt;Java Cloning - Copy Constructor versus Cloning&lt;/a&gt;, I had discussed Java cloning in detail and explained every concept like what is cloning, how does it work, what are the necessary steps we need to follow to implement cloning, how to use Object.clone(), what is Shallow and Deep cloning, how we can achieve cloning using Serialization and Copy constructors and advantages copy of copy constructors over Java cloning.  &lt;/p&gt;

&lt;p&gt;If you have read those articles you can easily understand why it is good to use Copy constructors over cloning or Object.clone().&lt;/p&gt;

&lt;p&gt;And in this article, I am going to discuss why even copy constructors are not sufficient?  &lt;/p&gt;

&lt;p&gt;&lt;a href="////2.bp.blogspot.com/-55GvTwONJJQ/WHzFc4zE-8I/AAAAAAAAKY0/C0mGFqV0ohkfItyuPsuUprF8J5hAP3JegCK4B/s1600/Why-Copy-Constructors-Are-Not-Sufficient.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1vIEniOc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://2.bp.blogspot.com/-55GvTwONJJQ/WHzFc4zE-8I/AAAAAAAAKY0/C0mGFqV0ohkfItyuPsuUprF8J5hAP3JegCK4B/s640/Why-Copy-Constructors-Are-Not-Sufficient.png" alt="Why-Copy-Constructors-Are-Not-Sufficient" title="Why-Copy-Constructors-Are-Not-Sufficient"&gt;&lt;/a&gt;  &lt;/p&gt;

&lt;p&gt;Yes, you are reading it right copy constructors are not sufficient by themselves, copy constructors are not polymorphic because constructors do not get inherited to the child class from the parent class. If we try to refer a child object from parent class reference, we will face problems in cloning it using the copy constructor. To understand it let’s take examples of two classes Mammal and Human where Human extends Mammal, Mammal class have one field type and two constructors, one to create the object and one copy constructor to create a copy of an object  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Mammal {

    protected String type;

    public Mammal(String type) { this.type = type; }

    public Mammal(Mammal original) { this.type = original.type; }

    public String getType() { return type; }

    public void setType(String type) { this.type = type; }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Mammal mammal = (Mammal) o;

        if (!type.equals(mammal.type)) return false;

        return true;
    }

    @Override
    public int hashCode() { return type.hashCode(); }

    @Override
    public String toString() {
        return "Mammal{" + "type='" + type + "'}";
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And Human class which extends Mammal class, have one name field, one normal constructor and one copy constructor to create a copy  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Human extends Mammal {

    protected String name;

    public Human(String type, String name) {
        super(type);
        this.name = name;
    }

    public Human(Human original) {
        super(original.type);
        this.name = original.name;
    }

    public String getName() { return name; }

    public void setName(String name) { this.name = name; }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        if (!super.equals(o)) return false;

        Human human = (Human) o;

        if (!type.equals(human.type)) return false;
        if (!name.equals(human.name)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + name.hashCode();
        return result;
    }

    @Override
    public String toString() {
        return "Human{" + "type='" + type + "', name='" + name + "'}";
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;Here in both copy constructors we are doing deep cloning.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now let’s create objects for both classes  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Mammal mammal = new Mammal("Human");
Human human = new Human("Human", "Naresh");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now if we want to create a clone for mammal or human, we can simply do it by calling their respective copy constructor  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Mammal clonedMammal = new Mammal(mammal);
Human clonedHuman = new Human(human);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We will get no error in doing this and both objects will be cloned successfully, as we can see below tests  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;System.out.println(mammal == clonedMammal); // false
System.out.println(mammal.equals(clonedMammal)); // true

System.out.println(human == clonedHuman); // false
System.out.println(human.equals(clonedHuman)); // true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;But what if we try to refer object of Human from the reference of Mammal  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Mammal mammalHuman = new Human("Human", "Mahesh");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In order to clone mammalHuman, we can not use constructor Human, It will give us compilation error because type mammalHuman is Mammal and constructor of Human class accept Human.  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Mammal clonedMammalHuman = new Human(mammalHuman); // compilation error
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And if we try clone mammalHuman using copy constructor of Mammal, we will get the object of Mammal instead of Human but mammalHuman holds an object of Human  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Mammal clonedMammalHuman = new Mammal(mammalHuman);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;So both mammalHuman and clonedMammalHuman are not the same objects as you see in the output below code  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;System.out.println("Object " + mammalHuman + " and copied object " + clonedMammalHuman + " are == : " + (mammalHuman == clonedMammalHuman));
System.out.println("Object " + mammalHuman + " and copied object " + clonedMammalHuman + " are equal : " + (mammalHuman.equals(clonedMammalHuman)) + "\n");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Output:  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Object Human{type='Human', name='Mahesh'} and copied object Mammal{type='Human'} are == : false
Object Human{type='Human', name='Mahesh'} and copied object Mammal{type='Human'} are equal : false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As we can see copy constructors suffer from inheritance problems and they are not polymorphic as well. So how can we solve this problem, Well there are various solutions like creating static Factory methods or creating some generic class which will do this for us and the list will go on?  &lt;/p&gt;

&lt;p&gt;But there is a very easy solution which will require copy constructors and will be polymorphic as well. We can solve this problem using defensive copy methods, a method which we are going to include in our classes and call copy constructor from it and again override it the child class and call its copy constructor from it.  &lt;/p&gt;

&lt;p&gt;Defensive copy methods will also give us the advantage of dependency injection, we can inject dependency instead of making our code tightly coupled we can make it loosely coupled, we can even create an interface which will define our defensive copy method and then implement it in our class and override that method.  &lt;/p&gt;

&lt;p&gt;So in Mammal class, we will create a no-argument method cloneObject however, we are free to name this method anything like clone or copy or copyInstance  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public Mammal cloneObject() {
    return new Mammal(this);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And we can override same in “Human” class  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Override
public Human cloneObject() {
    return new Human(this);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now to clone mammalHuman we can simply say  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Mammal clonedMammalHuman = mammalHuman.clone();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And for the last two sys out we will get below output which is our expected behaviour.  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Object Human{type='Human', name='Mahesh'} and copied object Human{type='Human', name='Mahesh'} are == : false
Object Human{type='Human', name='Mahesh'} and copied object Human{type='Human', name='Mahesh'} are equal : true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As we can see apart from getting the advantage of polymorphism this option also gives us freedom from passing any argument.&lt;/p&gt;

&lt;p&gt;You can find the complete source code for this article on this &lt;a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/CopyConstructorExample.java"&gt;Github Repository&lt;/a&gt; and please feel free to provide your valuable feedback.&lt;/p&gt;

</description>
      <category>java</category>
      <category>cloning</category>
      <category>deepcopy</category>
    </item>
    <item>
      <title>JPA Auditing: Persisting Audit Logs Automatically using EntityListeners</title>
      <dc:creator>Naresh Joshi</dc:creator>
      <pubDate>Wed, 12 Jun 2019 16:30:59 +0000</pubDate>
      <link>https://dev.to/njnareshjoshi/jpa-auditing-persisting-audit-logs-automatically-using-entitylisteners-238p</link>
      <guid>https://dev.to/njnareshjoshi/jpa-auditing-persisting-audit-logs-automatically-using-entitylisteners-238p</guid>
      <description>&lt;p&gt;In one of my article &lt;a href="https://programmingmitra.blogspot.in/2017/02/automatic-spring-data-jpa-auditing-saving-CreatedBy-createddate-lastmodifiedby-lastmodifieddate-automatically.html" rel="noopener noreferrer"&gt;Spring Data JPA Auditing: Saving CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate automatically&lt;/a&gt;, I have discussed why Auditing is important for any business application and how we can use Spring Data JPA automate it.  &lt;/p&gt;

&lt;p&gt;I have also discussed how Spring Data uses JPA’s &lt;strong&gt;EntityListeners&lt;/strong&gt; and &lt;strong&gt;callback methods&lt;/strong&gt; to automatically update CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate properties.  &lt;/p&gt;

&lt;p&gt;Well, here in this article I am going dig a little bit more and discuss how we can use JPA EntityListeners to create audit logs and keep information of every insert, update and delete operation on our data.  &lt;/p&gt;

&lt;p&gt;I will take the File entity example from the previous article and walk you through the necessary steps and code portions you will need to include in our project to automate the Auditing process.  &lt;/p&gt;

&lt;p&gt;We will use Spring Boot, Spring Data JPA (Because it gives us complete JPA functionality plus some nice customization by Spring), MySql to demonstrate this.&lt;/p&gt;

&lt;p&gt;We will need to add below parent and dependencies to our pom file  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;parent&amp;gt;
    &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;spring-boot-starter-parent&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;1.5.1.RELEASE&amp;lt;/version&amp;gt;
    &amp;lt;relativePath/&amp;gt;
&amp;lt;/parent&amp;gt;

&amp;lt;dependencies&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-boot-starter-data-jpa&amp;lt;/artifactId&amp;gt;
    &amp;lt;/dependency&amp;gt;

    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;mysql&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;mysql-connector-java&amp;lt;/artifactId&amp;gt;
        &amp;lt;scope&amp;gt;runtime&amp;lt;/scope&amp;gt;
    &amp;lt;/dependency&amp;gt;
&amp;lt;/dependencies&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Implementing JPA Callback Methods using annotations @PrePersist, @PreUpdate, @PreRemove
&lt;/h3&gt;

&lt;p&gt;JPA provides us with the functionality to define callback methods for any entity using annotations &lt;strong&gt;@PrePersist&lt;/strong&gt;, &lt;strong&gt;@PreUpdate&lt;/strong&gt;, &lt;strong&gt;@PreRemove&lt;/strong&gt; and these methods will get invoked before their respective life cycle event.&lt;/p&gt;

&lt;p&gt;Similar to pre-annotations, JPA also provides post annotations like &lt;strong&gt;@PostPersist&lt;/strong&gt;, &lt;strong&gt;@PostUpdate&lt;/strong&gt;, &lt;strong&gt;@PostRemove, *&lt;em&gt;and *&lt;/em&gt;@PostLoad&lt;/strong&gt;. We can use them to define callback methods which will get triggered after the event.  &lt;/p&gt;

&lt;p&gt;&lt;a href="//3.bp.blogspot.com/-Jrwc5quKJAY/WKA_RGPIW8I/AAAAAAAAKg0/FSGY7lGEWfYzPpDIxVgK9NFzwnMhFbO0wCK4B/s1600/JPA-Automatic-Auditing-Saving-Audit-Logs.png"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2F3.bp.blogspot.com%2F-Jrwc5quKJAY%2FWKA_RGPIW8I%2FAAAAAAAAKg0%2FFSGY7lGEWfYzPpDIxVgK9NFzwnMhFbO0wCK4B%2Fs1600%2FJPA-Automatic-Auditing-Saving-Audit-Logs.png" title="JPA-Automatic-Auditing-Saving-Audit-Logs" alt="JPA-Automatic-Auditing-Saving-Audit-Logs"&gt;&lt;/a&gt;  &lt;/p&gt;

&lt;p&gt;Name of the annotation can tell you their respective event e.g @PrePersist - Before entity persists and @PostUpdate - After entity gets updated and this is the same for other annotations as well.  &lt;/p&gt;
&lt;h3&gt;
  
  
  Defining callback methods inside the entity
&lt;/h3&gt;

&lt;p&gt;We can define callback methods inside our entity class but we need to follow some rules like internal callback methods should always return void and take no argument. They can have any name and any access level and can also be static.  &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entity
public class File {

    @PrePersist
    public void prePersist() { // Persistence logic }

    @PreUpdate
    public void preUpdate() { //Updation logic }

    @PreRemove
    public void preRemove() { //Removal logic }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Defining callback methods in an external class and use @EntityListeners
&lt;/h3&gt;

&lt;p&gt;We can also define our callback methods in an external listener class in a manner that they should always return void and accepts a target object as the argument. However, they can have any name and any access level and can also be static.  &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class FileEntityListener {
    @PrePersist
    public void prePersist(File target) { // Persistence logic }

    @PreUpdate
    public void preUpdate(File target) { //Updation logic }

    @PreRemove
    public void preRemove(File target) { //Removal logic }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And we will need to register this FileEntityListener class on File entity or its superclass by using &lt;strong&gt;@EntityListeners&lt;/strong&gt; annotation  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entity
@EntityListeners(FileEntityListener.class)
class File extends Auditable&amp;lt;String&amp;gt; {

    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    private String content;

    // Fields, Getters and Setters
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Advantages of using @EntityListeners
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  First of all, We should not write any kind of business logic in our entity classes and follow the Single Responsibility Principle. Every entity class should be &lt;a href="https://programmingmitra.blogspot.in/2016/05/plain-old-java-object-pojo-explained.html" rel="noopener noreferrer"&gt;POJO (Plain Old Java Object)&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;  We can have only one callback method for a particular event in a single class e.g. only one callback method with @PrePresist is allowed in a class. While we can define more than one listener class in @EntityListeners and every listener class can have a @PrePersist.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For example, I have used @EntityListeners on File and provided FileEntityListener class to it and I have also extended an Auditable class in File class.&lt;/p&gt;

&lt;p&gt;The Auditable class itself have a @EntityListeners on it with AuditingEntityListener class because I am using this class to persist createdBy and other above-mentioned properties, You can check my previous article &lt;a href="https://programmingmitra.blogspot.in/2017/02/automatic-spring-data-jpa-auditing-saving-CreatedBy-createddate-lastmodifiedby-lastmodifieddate-automatically.html" rel="noopener noreferrer"&gt;Spring Data JPA Auditing: Saving CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate automatically&lt;/a&gt; for more details.  &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable&amp;lt;U&amp;gt; {

    @CreatedBy
    protected U createdBy;

    @CreatedDate
    @Temporal(TIMESTAMP)
    protected Date createdDate;

    @LastModifiedBy
    protected U lastModifiedBy;

    @LastModifiedDate
    @Temporal(TIMESTAMP)
    protected Date lastModifiedDate;

    // Getters and Setters
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We will also need to provide getters, setters, constructors, toString and equals methods to all the entities. However, you may like to look &lt;a href="https://programmingmitra.blogspot.in/2017/01/Project-Lombok-The-Boilerplate-Code-Extractor.html" rel="noopener noreferrer"&gt;Project Lombok: The Boilerplate Code Extractor&lt;/a&gt; if you want to auto-generate these things.  &lt;/p&gt;

&lt;p&gt;Now we are all set and we need to implement our logging strategy, we can store history logs of the File in a separate history table FileHistory.  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entity
@EntityListeners(AuditingEntityListener.class)
public class FileHistory {

    @Id
    @GeneratedValue
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "file_id", foreignKey = @ForeignKey(name = "FK_file_history_file"))
    private File file;

    private String fileContent;

    @CreatedBy
    private String modifiedBy;

    @CreatedDate
    @Temporal(TIMESTAMP)
    private Date modifiedDate;

    @Enumerated(STRING)
    private Action action;

    public FileHistory() {
    }

    public FileHistory(File file, Action action) {
        this.file = file;
        this.fileContent = file.toString();
        this.action = action;
    }

    // Getters, Setters
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here Action is an enum  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public enum Action {

    INSERTED("INSERTED"),
    UPDATED("UPDATED"),
    DELETED("DELETED");

    private final String name;

    private Action(String value) {
        this.name = value;
    }

    public String value() {
        return this.name;
    }

    @Override
    public String toString() {
        return name;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And we will need to insert an entry in FileHistory for every insert, update, delete operation and we need to write that logic inside our FileEntityListener class. For this purpose, we will need to inject either repository class or EntityManager in FileEntityListener class.  &lt;/p&gt;

&lt;h3&gt;
  
  
  Injecting Spring Managed Beans like EntityManager in EntityListeners
&lt;/h3&gt;

&lt;p&gt;But here we have a problem, EntityListeners are instantiated by JPA not Spring, So Spring cannot inject any Spring-managed bean e.g. EntityManager in any EntityListeners.  &lt;/p&gt;

&lt;p&gt;So if you try to auto-wire EntityManager inside FileEntityListener class, it will not work  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Autowired EntityManager entityManager; //Will not work and entityManager will be null always
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;I have also written a separate article on how to &lt;a href="https://programmingmitra.blogspot.in/2017/03/AutoWiring-Spring-Beans-Into-Classes-Not-Managed-By-Spring-Like-JPA-Entity-Listeners.html" rel="noopener noreferrer"&gt;AutoWire Spring Beans Into Classes Not Managed By Spring Like JPA Entity Listeners&lt;/a&gt;, you can read it if you want to know more.  &lt;/p&gt;

&lt;p&gt;And I am using the same idea here to make it work, we will create a utility class to fetch Spring managed beans for us  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Service
public class BeanUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static &amp;lt;T&amp;gt; T getBean(Class&amp;lt;T&amp;gt; beanClass) {
        return context.getBean(beanClass);
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And now we will write history record creation logic inside FileEntityListener  &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class FileEntityListener {

    @PrePersist
    public void prePersist(File target) {
        perform(target, INSERTED);
    }

    @PreUpdate
    public void preUpdate(File target) {
        perform(target, UPDATED);
    }

    @PreRemove
    public void preRemove(File target) {
        perform(target, DELETED);
    }

    @Transactional(MANDATORY)
    private void perform(File target, Action action) {
        EntityManager entityManager = BeanUtil.getBean(EntityManager.class);
        entityManager.persist(new FileHistory(target, action));
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And now if we will try to persist or update and file object these auditing properties will automatically get saved.  &lt;/p&gt;

&lt;p&gt;You can find the complete code on this &lt;a href="https://github.com/njnareshjoshi/articles/tree/master/spring-data-jpa-auditing" rel="noopener noreferrer"&gt;Github Repository&lt;/a&gt; and please feel free to provide your valuable feedback.&lt;/p&gt;

</description>
      <category>java</category>
      <category>springboot</category>
      <category>jpa</category>
    </item>
    <item>
      <title>How Does JVM Handle Polymorphism (Method Overloading and Overriding) Internally</title>
      <dc:creator>Naresh Joshi</dc:creator>
      <pubDate>Sun, 09 Jun 2019 13:11:38 +0000</pubDate>
      <link>https://dev.to/njnareshjoshi/how-does-jvm-handle-polymorphism-method-overloading-and-overriding-internally-2m26</link>
      <guid>https://dev.to/njnareshjoshi/how-does-jvm-handle-polymorphism-method-overloading-and-overriding-internally-2m26</guid>
      <description>&lt;p&gt;In my previous article &lt;a href="https://programmingmitra.blogspot.in/2017/05/everything-about-method-overloading-vs-method-overriding.html" rel="noopener noreferrer"&gt;Everything About Method Overloading Vs Method Overriding&lt;/a&gt;, I have discussed method overloading and overriding, their rules and differences.  &lt;/p&gt;

&lt;p&gt;In this article, we will see How Does JVM Handle Method Overloading And Overriding Internally, how JVM identifies which method should get called.  &lt;/p&gt;

&lt;p&gt;Let’s take the example of parent class&lt;code&gt;Mammal&lt;/code&gt; and a child&lt;code&gt;Human&lt;/code&gt; classes from our previous blog to understand it more clearly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;OverridingInternalExample&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Mammal&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;speak&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt; &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"ohlllalalalalalaoaoaoa"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Human&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;Mammal&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

        &lt;span class="nd"&gt;@Override&lt;/span&gt;
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;speak&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt; &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Hello"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="o"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;// Valid overload of speak&lt;/span&gt;
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;speak&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;language&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;language&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;equals&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Hindi"&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt; &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Namaste"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Hello"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;

        &lt;span class="nd"&gt;@Override&lt;/span&gt;
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;toString&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s"&gt;"Human Class"&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt; &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="c1"&gt;//  Code below contains the output and bytecode of the method calls&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;Mammal&lt;/span&gt; &lt;span class="n"&gt;anyMammal&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Mammal&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;anyMammal&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;speak&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;  &lt;span class="c1"&gt;// Output - ohlllalalalalalaoaoaoa&lt;/span&gt;
        &lt;span class="c1"&gt;// 10: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V&lt;/span&gt;

        &lt;span class="nc"&gt;Mammal&lt;/span&gt; &lt;span class="n"&gt;humanMammal&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Human&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;humanMammal&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;speak&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// Output - Hello&lt;/span&gt;
        &lt;span class="c1"&gt;// 23: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V&lt;/span&gt;

        &lt;span class="nc"&gt;Human&lt;/span&gt; &lt;span class="n"&gt;human&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Human&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;human&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;speak&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// Output - Hello&lt;/span&gt;
        &lt;span class="c1"&gt;// 36: invokevirtual #7 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:()V&lt;/span&gt;

        &lt;span class="n"&gt;human&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;speak&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Hindi"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Output - Namaste&lt;/span&gt;
        &lt;span class="c1"&gt;// 42: invokevirtual #9 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:(Ljava/lang/String;)V&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can answer this answer in two ways, Logical way and Physical way, let's take a look at the logical way.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Logical Way
&lt;/h2&gt;

&lt;p&gt;Logically we can say, during compilation phase calling method is considered from the reference type. But at execution time method will be called from the object which the reference is holding.  &lt;/p&gt;

&lt;p&gt;For Example on &lt;code&gt;humanMammal.speak();&lt;/code&gt; line compiler will say &lt;code&gt;Mammal.speak()&lt;/code&gt; is getting called because &lt;code&gt;humanMammal&lt;/code&gt; is of type &lt;code&gt;Mammal&lt;/code&gt; . But during execution JVM knows that &lt;code&gt;humanMammal&lt;/code&gt; is holding a &lt;code&gt;Human's&lt;/code&gt; object so &lt;code&gt;Human.speak()&lt;/code&gt; will get called.  &lt;/p&gt;

&lt;p&gt;Well, it is pretty simple until we keep it at the conceptual level only. Once we get the doubt that how JVM is handling all this internally? or how JVM is calculating which method it should call.  &lt;/p&gt;

&lt;p&gt;Also, we know that overloaded methods are not called polymorphic and get resolved at compile time and this is why sometimes method overloading is also known as** compile-time polymorphism or early/static binding**.  &lt;/p&gt;

&lt;p&gt;But overridden methods get resolved at runtime time because the compiler does not know that, the object which we are assigning to our reference have overridden the method or not.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Physical Way
&lt;/h2&gt;

&lt;p&gt;In this section, we will try to find out physical proof of all aforementioned statements and to find them we will read the bytecode of our program which we can do by executing &lt;code&gt;javap -verbose OverridingInternalExample&lt;/code&gt;. By using the &lt;code&gt;-verbose&lt;/code&gt; option we will get the descriptive bytecode same as our Java program.  &lt;/p&gt;

&lt;p&gt;Above command shows the bytecode in two sections  &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Constant Pool:&lt;/strong&gt; holds almost everything which is necessary for our program’s execution e.g. method references (&lt;code&gt;#Methodref&lt;/code&gt;), Class objects ( &lt;code&gt;#Class&lt;/code&gt; ), string literals ( &lt;code&gt;#String&lt;/code&gt; ), please click on image to zoom.  &lt;/p&gt;

&lt;p&gt;&lt;a href="//2.bp.blogspot.com/-q3LKSKxk4B4/WT67WYY0gaI/AAAAAAAALSQ/ovoyKut4JwQU4nXBtTQntmSrgyf7HzojQCK4B/s1600/java-constant-pool-method-table.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oHp-C3Ic--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://2.bp.blogspot.com/-q3LKSKxk4B4/WT67WYY0gaI/AAAAAAAALSQ/ovoyKut4JwQU4nXBtTQntmSrgyf7HzojQCK4B/s1600/java-constant-pool-method-table.png" title="java-method-area-or-constant-pool-or-method-table" alt="java-method-area-or-constant-pool-or-method-table" width="800" height="432"&gt;&lt;/a&gt;  &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Program’s Bytecode&lt;/strong&gt;: executable bytecode instructions, please click on image to zoom.  &lt;/p&gt;

&lt;p&gt;&lt;a href="//4.bp.blogspot.com/-3J5Gu7HRR3U/WT67qoWNaHI/AAAAAAAALSY/mx_27LmbToA0JE151OjXF0qxHtzGfBNVACK4B/s1600/method-overloading-overriding-internals-byte-code.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--lBjYy0-L--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://4.bp.blogspot.com/-3J5Gu7HRR3U/WT67qoWNaHI/AAAAAAAALSY/mx_27LmbToA0JE151OjXF0qxHtzGfBNVACK4B/s1600/method-overloading-overriding-internals-byte-code.png" title="method-overloading-overriding-internals-byte-code" alt="method-overloading-overriding-internals-byte-code" width="800" height="365"&gt;&lt;/a&gt;  &lt;/p&gt;

&lt;h2&gt;
  
  
  Why Method overloading is called static binding
&lt;/h2&gt;

&lt;p&gt;In afore-mentioned code &lt;code&gt;humanMammal.speak()&lt;/code&gt; the compiler will say &lt;code&gt;speak()&lt;/code&gt; is getting called from &lt;code&gt;Mammal&lt;/code&gt; but at execution time it will be called from the object which &lt;code&gt;humanMammal&lt;/code&gt; is holding, which is the object of the &lt;code&gt;Human&lt;/code&gt; class.  &lt;/p&gt;

&lt;p&gt;And by looking at the above code and images we can see that the bytecodes of &lt;code&gt;humanMammal.speak()&lt;/code&gt; , &lt;code&gt;human.speak()&lt;/code&gt; and &lt;code&gt;human.speak("Hindi")&lt;/code&gt; are totally different because the compiler is able to differentiate between them based on the class reference.  &lt;/p&gt;

&lt;p&gt;So in the case of method overloading compiler is able to identify the bytecode instructions and method’s address at compile time and that is why it is also known as &lt;strong&gt;static binding or compile time polymorphism&lt;/strong&gt;.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Why Method overriding is called dynamic binding
&lt;/h2&gt;

&lt;p&gt;Bytecode for &lt;code&gt;anyMammal.speak()&lt;/code&gt; and &lt;code&gt;humanMammal.speak()&lt;/code&gt; are same ( &lt;code&gt;invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V&lt;/code&gt; ) because according to compiler both methods are called on &lt;code&gt;Mammal&lt;/code&gt; reference.  &lt;/p&gt;

&lt;p&gt;So now the question comes if both method calls have same bytecode then how does JVM know which method to call?  &lt;/p&gt;

&lt;p&gt;Well, the answer is hidden in the bytecode itself and it is &lt;code&gt;invokevirtual&lt;/code&gt; instruction, according to JVM specification  &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;invokevirtual invokes an instance method of an object, dispatching on the (virtual) type of the object. This is the normal method dispatch in the Java programming language.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;JVM uses the &lt;code&gt;invokevirtual&lt;/code&gt; instruction to invoke Java equivalent of the C++ virtual methods. In C++ if we want to override one method in another class we need to declare it as &lt;code&gt;virtual&lt;/code&gt;, But in Java, all methods are virtual by default (except final and static methods) because we can override every method in the child class.  &lt;/p&gt;

&lt;p&gt;Operation &lt;code&gt;invokevirtual&lt;/code&gt; accepts a pointer to method reference call ( &lt;code&gt;#4&lt;/code&gt; an index into the constant pool)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;invokevirtual &lt;span class="c"&gt;#4   // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that method reference #4 again refers to a method name and Class reference&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;#4 = Methodref   #2.#27   // org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V&lt;/span&gt;
&lt;span class="c"&gt;#2 = Class   #25   // org/programming/mitra/exercises/OverridingInternalExample$Mammal&lt;/span&gt;
&lt;span class="c"&gt;#25 = Utf8   org/programming/mitra/exercises/OverridingInternalExample$Mammal&lt;/span&gt;
&lt;span class="c"&gt;#27 = NameAndType   #35:#17   // speak:()V&lt;/span&gt;
&lt;span class="c"&gt;#35 = Utf8   speak&lt;/span&gt;
&lt;span class="c"&gt;#17 = Utf8&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All these references combinedly used to get a reference to a method and class in which the method is to be found. This is also mentioned in JVM Specification  &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The Java virtual machine does not mandate any particular internal structure for objects 4.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;And the bookmark 4 states  &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In some of Oracle’s implementations of the Java virtual machine, a reference to a class instance is a pointer to a handle that is itself a pair of pointers: one to a table containing the methods of the object and a pointer to the Class object that represents the type of the object, and the other to the memory allocated from the heap for the object data.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It means every reference variable holds two hidden pointers  &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; A pointer to a table which again holds methods of the object and a pointer to the Class object. e.g. [speak(), speak(String) Class object]&lt;/li&gt;
&lt;li&gt; A pointer to the memory allocated on the heap for that object’s data e.g. values of instance variables.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;But again the question comes, how &lt;code&gt;invokevirtual&lt;/code&gt; internally do this? Well, no one can answer this because it depends on JVM implementation and it varies from JVM to JVM.  &lt;/p&gt;

&lt;p&gt;And from the above statements, we can conclude that an object reference indirectly holds a reference/pointer to a table which holds all the method references of that object. Java has borrowed this concept from C++ and this table is known by various names which such as &lt;a href="https://en.wikipedia.org/wiki/Virtual_method_table" rel="noopener noreferrer"&gt;virtual method table ( &lt;strong&gt;VMT&lt;/strong&gt; ), virtual function table ( ** vftable** ), virtual table ( &lt;strong&gt;vtable&lt;/strong&gt; ), dispatch table&lt;/a&gt;.  &lt;/p&gt;

&lt;p&gt;We can not sure how &lt;code&gt;vtable&lt;/code&gt; is implemented in Java because it is JVM dependent. But we can expect that it will be following the same strategy as C++ where &lt;code&gt;vtable&lt;/code&gt; is an array like structure which holds method names and their references on array indices. And whenever JVM tries to execute a virtual method it always asks the &lt;code&gt;vtable&lt;/code&gt; for its address.  &lt;/p&gt;

&lt;p&gt;There is only one &lt;code&gt;vtable&lt;/code&gt; per class means it is unique and the same for all objects of a class similar to &lt;code&gt;Class&lt;/code&gt; object. I have discussed more on &lt;code&gt;Class&lt;/code&gt; object in my articles &lt;a href="https://programmingmitra.blogspot.in/2016/10/why-outer-java-class-cant-be-static.html" rel="noopener noreferrer"&gt;Why an outer Java class can’t be static&lt;/a&gt; and &lt;a href="https://programmingmitra.blogspot.in/2016/06/why-java-is-purely-object-oriented-or-why-not.html" rel="noopener noreferrer"&gt;Why Java is Purely Object-Oriented Language Or Why Not&lt;/a&gt;.  &lt;/p&gt;

&lt;p&gt;So there is only one &lt;code&gt;vtable&lt;/code&gt; for &lt;code&gt;Object&lt;/code&gt; class which contains all 11 methods (if we don't count registerNatives) and references to their respective method bodies.  &lt;/p&gt;

&lt;p&gt;&lt;a href="//4.bp.blogspot.com/-OmB72b_upTM/WT7PkecSHMI/AAAAAAAALS0/nH5hmwdBMwMb8g-WycCsPpfn8bkh-pq3wCK4B/s1600/vtable-of-object.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--UvTRBGHE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://4.bp.blogspot.com/-OmB72b_upTM/WT7PkecSHMI/AAAAAAAALS0/nH5hmwdBMwMb8g-WycCsPpfn8bkh-pq3wCK4B/s640/vtable-of-object.png" title="vtable-of-object" alt="vtable-of-object" width="544" height="187"&gt;&lt;/a&gt;  &lt;/p&gt;

&lt;p&gt;When JVM loads the &lt;code&gt;Mammal&lt;/code&gt; class into memory it creates a &lt;code&gt;Class&lt;/code&gt; object for it and creates a &lt;code&gt;vtable&lt;/code&gt; which contains all the methods from the vtable of Object class with the same references (Because &lt;code&gt;Mammal&lt;/code&gt; is not overriding any method from Object) and adds a new entry for &lt;code&gt;speak&lt;/code&gt; method.  &lt;/p&gt;

&lt;p&gt;&lt;a href="//1.bp.blogspot.com/-asDExe0Qg18/WT7PuZdv0hI/AAAAAAAALS8/rkdwAGMRrAISOe_2mIeXTg8PTUCFxDTRQCK4B/s1600/vtable-of-mammal.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--a1paFn3D--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://1.bp.blogspot.com/-asDExe0Qg18/WT7PuZdv0hI/AAAAAAAALS8/rkdwAGMRrAISOe_2mIeXTg8PTUCFxDTRQCK4B/s640/vtable-of-mammal.png" title="vtable-human" alt="vtable-human" width="567" height="164"&gt;&lt;/a&gt;  &lt;/p&gt;

&lt;p&gt;Now here comes the turn of &lt;code&gt;Human&lt;/code&gt; class and now JVM will copy all entries from the &lt;code&gt;vtable&lt;/code&gt; of &lt;code&gt;Mammal&lt;/code&gt; class to the &lt;code&gt;vtable&lt;/code&gt; of &lt;code&gt;Human&lt;/code&gt; and adds a new entry for the overloaded version of &lt;code&gt;speak(String)&lt;/code&gt;.  &lt;/p&gt;

&lt;p&gt;JVM knows that &lt;code&gt;Human&lt;/code&gt; class has overridden two methods one is &lt;code&gt;toString()&lt;/code&gt; from &lt;code&gt;Object&lt;/code&gt; and second is &lt;code&gt;speck()&lt;/code&gt; from &lt;code&gt;Mammal&lt;/code&gt; . Now instead of creating new entries for these methods with updated references. JVM will modify the references to the already present methods on the same index where they were present earlier and will keep the same method names.  &lt;/p&gt;

&lt;p&gt;&lt;a href="//3.bp.blogspot.com/-DuoCzjUxQ8M/WT7Ru7OXi9I/AAAAAAAALTM/OHsjsEL9Bx83siSo3uKWSa5tUiL5zOiRgCK4B/s1600/vtable-of-human.png"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsyqeopjb0wyerfcmo8dg.png" width="546" height="191"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;invokevirtual&lt;/code&gt; causes the JVM to treat the value at method reference &lt;code&gt;#4&lt;/code&gt;, not as an address but as the name of a method to look up in the &lt;code&gt;vtable&lt;/code&gt; for the current object.  &lt;/p&gt;

&lt;p&gt;I hope now it would have become a little bit clear that how the JVM mixes &lt;code&gt;constant pool&lt;/code&gt; entries and &lt;code&gt;vtable&lt;/code&gt; to conclude which method it is going to call.&lt;/p&gt;

&lt;p&gt;You can find the complete code on this &lt;a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/OverridingInternalExample.java" rel="noopener noreferrer"&gt;Github Repository&lt;/a&gt; and please feel free to provide your valuable feedback.&lt;/p&gt;

</description>
      <category>java</category>
      <category>polymorphism</category>
      <category>overriding</category>
      <category>jvm</category>
    </item>
    <item>
      <title>"Hi - I'm new here!" </title>
      <dc:creator>Naresh Joshi</dc:creator>
      <pubDate>Tue, 28 May 2019 17:00:23 +0000</pubDate>
      <link>https://dev.to/njnareshjoshi/hi-i-m-new-here-1nmj</link>
      <guid>https://dev.to/njnareshjoshi/hi-i-m-new-here-1nmj</guid>
      <description>&lt;p&gt;Hello everyone, I am Naresh Joshi and this is my first post on dev.to, thanks in advance for checking it out!&lt;/p&gt;

&lt;p&gt;I recently found dev.to community and I am impressed by the articles and discussions developers can have here.&lt;/p&gt;

&lt;p&gt;I am a Software Developer, working mostly on Java programming and its related frameworks like Spring, JPA, Hibernate.&lt;/p&gt;

&lt;p&gt;Currently, I am working Scala and Spark and I like it.&lt;/p&gt;

&lt;p&gt;I love to create my own thoughts about anything which comes to my notice and I think we should always have our own thinking on everything rather than just following what others think.&lt;/p&gt;

&lt;p&gt;I publish my thoughts on my blog ProgrammingMitra(programmingmitra.com) and I would love to contribute to dev.to!&lt;/p&gt;

&lt;p&gt;I am looking forward to engaging in this community and talk to you all!&lt;/p&gt;

</description>
      <category>firstpost</category>
    </item>
  </channel>
</rss>
