Monday 31 October 2016

Java Source World: Covariant Return Type in Java

Covariant Return Type in Java | Java Source World
                                                                    Javasourceworld                   A Java quick reference blog 




Covariant Return Type in Java


The covariant return type specifies that the return type may vary in the same direction as the subclass.

Before Java5, it was not possible to override any method by changing the return type. But now, since Java5, it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type. Let's take a simple example:

Example: 

package com.core;
class A{
     
      A getA(){
            return this;
      }
}
class B extends A {
     
     
      B getA(){
            return this;
      }
      void message(){
            System.out.println("Message me");
      }
}

public class TestCovariant {
      public static void main(String[] args) {
            new B().getA().message();
      }
}
Output:Message me


As you can see in the above example, the return type of the get() method of A class is A but the return type of the get() method of B class is B. Both methods have different return type but it is method overriding. This is known as covariant return type.


Advantages:
  • Covariant return type helps to maintain backward compatibility.
  • We can always work at the appropriate level of abstraction



Also you may like the fallowing posts:

Fallow Spring Tutorials:



                                                               Javasourceworld                   A Java quick reference blog
Read More »

Sunday 30 October 2016

Java Source World: Association, Aggregation, Composition

Association, Aggregation, Composition | Java Source World
                                                                  Javasourceworld                   A Java quick reference blog



Association, Aggregation, Composition




Association:



Association is a relationship where all objects have their own life cycle and there is no owner. 

For Example: Teacher and Student

Explanation:

A single Teacher object can have more Students or A single Student can associate with multiple Teachers.

But there is no ownership between these two objects and they have their won lifecycle. Both can be created and deleted independently.

Aggregation:


Aggregation is a specialized form of Association where all objects have their own lifecycle, but there is ownership and a child object cannot belong to another parent object.

For Example: Department and Teacher.

Explanation:

A single Teacher cannot belong to multiple Departments, but if we delete the department the teacher object will not be destroyed.

We can think of it is a "Has-A" relationship.


Composition:


Composition is a specialized form of Aggregation and we can call this as a "death" relationship. It is a strong type of Aggreation. Child object doesn't have their lifecycle and If parent object deletes all child objects will also be deleted. 

For Example: Bank and Accounts

Bank can contain multiple Accounts but there is no independent life of an Account and any Account can not belong to two different Banks. If we delete the Bank, the Account will automatically be deleted.



Now we will see the differences between Aggregation and Composition with similar examples.


Differences between Aggregation and Composition:



Aggregation:


Aggregation is an association in which one class belongs to a collection. This is part of a whole relationship wehere a part can exist without a whole.

For example:

A line item(list of products) is a whole and product is a part. If a line item is deleted then corresponding product need not be deleted. So aggregation has a weaker relationship.


Composition:


Composition is an association in which one class belongs to a collection. This is a part of a whole relationship where a part cannot exist without a whole. If a whole is deleted then all parts are deleted.

For example:

An Order is a whole and line items are parts. If an order is deleted then all corresponding line items for that order should be deleted. So composition has a stronger relationship.


Which one to favor composition or Inheritance?  


As per java docs, the guide is that inheritance should be only used when subclass "Is-A" super class.

Don't use inheritance just to get code reuse. If there is no "Is-A" relationship then use composition for code reuse. Over use of implementation inheritance (using the 'extends' keyword) can break all the sublcass if the superclass is modified.

Don't use inheritance just to get polymorphism. If there is no 'Is-A' relationship and all you want is polymorphism then use interface with composition, which gives you code reuse.







                                                                  Javasourceworld                   A Java quick reference blog
Read More »

Friday 28 October 2016

Java Source World: Equals and HashCode in java



Equals and HashCode in java


Equals and HashCode:


Equals and HashCode methods in Java are two fundamental methods from java.lang.Object class, which is used to compare equality of objects, primarily inside hash based collections such as Hashtable and HashMap. Both equals() and hashCode() are defined injava.lang.Object class and there default implementation is based upon Object information e.g. default equals() method return true, if two objects are exactly same i.e. they are pointing to same memory address, while default implementation of hashcode method return int and implemented as native method. Similar default implementation of toString() method, returns type of class, followed bymemory address in hex String. It's advised to override these method, based upon logicaland business rules e.g. String overrides equals to check equality of  two String based upon content, we have also seen and example implementation of equals() andhashCode for custom classes. Because of there usefulness and usage, they are also very popular in various level of Java Interviews, and In this tutorial, I am going to shared some of the really interesting questions from equals() and hashCode() method in Java. This question not only test your concept on both method, but also gives an opportunity to explore them more. By the way, if you are preparing for Java Interviews then I also suggest to take a look at Java Programming Interview Exposed book, one of the best book to prepare for Java programming interview. You will learn about everything you could expect in Java interviews.


Equals and HashCode Interview questions in Java

Here is my list of 10 interesting questions on both of these methods.  I have seen, programmer struggles to write equals() and hashCode() by hands, for a rich class, which contains different data types e.g. int, float, date etc. Reading those items and trying examples will give you enough confidence to face any question on equals and hashCode methods. I also suggest to read Effective Java Items on equals() and hashCode() to fill your gaps on knowledge of this two critical methods.

When you are writing equals() method, which other method or methods you need to override?
hashcode, is the right answer. Since equals and hashCode has there contract, so overriding one and not other, will break contract between them. By the way this question can lead on interesting discussion, if Interviewer likes to go on deep e.g. he may ask about what are those contracts, what happens if those contracts breaks etc. I like to give an example How equals and hashcode are used in hash based collections e.g. Hashtable, that leaves positive impression more often. You can also mention about compareTo() here to score some additional point, this method should also needs to be consistent with equals, which is another interesting question in our list.


Can two object which are not equal have same hashCode?
YES, two object, which are not equal by equals() method can still return same hashCode. By the way, this is one of the confusing bit of equals and hashcode contract.


How does get() method of HashMap works, if two keys has same hashCode?
This is the follow-up of previous interview questions on equals and hashcode, in fact some time this leads to discussion of the earlier point. When two key return same hashcode, they end-up in same bucket. Now, in order to find the correct value, you usedkeys.equals() method to compare with key stored in each Entry of linked list there. Remember to point out keys.equals() method, because that's what interviewer is looking for. 


Where have you written equals() and hashCode in your project?
This is to see, if developer has even written these methods or not. Of course almost all of Java programmer are exposed to this, you can point out value objects, Hibernate entities from your domain, where you have overridden equals and hashCode. Always gives examples from your domain and from your project, rather than a trivial example from a test program, because if Interviewer is asking this question, it means he is interested in examples form your domain.


Suppose your Class has an Id field, should you include in equals()? Why?
This question is asked to one of my reader as Hibernate Interview question, well including id is not a good idea in equals() method because this method should check equality based upon content and business rules. Also including id, which is mostly a database identifier and not available to transient object until they are saved into database.


What happens if equals() is not consistent with compareTo() method?
This is an interesting questions, which asked along with equals() and hashCode()contract. Some java.util.Set implementation e.g. SortedSet or it's concrete implementation TreeSet uses compareTo() method for comparing objects. IfcompareTo() is not consistent means doesn't return zero, if equals() method returnstrue, the it may break Set contract, which is not to avoid any duplicates.


What happens if you compare an object with null using equals()?
When a null object is passed as argument to equals() method, it should return false, it must not throw NullPointerException, but if you call equals method on reference, which is null it will throw NullPointerException. That’s why it’s better to use == operator for comparing null e.g. if(object != null) object.equals(anohterObject). By the way if you comparing String literal with another String object than you better callequals() method on literal rather than known object to avoid NPE, one of those simple tricks to avoid NullPointerException in Java.


What is difference in using instanceof and getClass() method for checking type inside equals?
This question was asked multiple times, sometime by looking at your equals() and hashCode implementation. Well key difference comes from point that instanceofoperator returns true, even if compared with sub class e.g. Subclass instanceof Super class is true, but with getClass() it's false. By using getClass() you ensure that yourequals() implementation doesn't return true if compared with sub class object. While if you use instanceof operator, you end up breaking symmetry rule for equals which says that if a.equals(b) is true than b.equals(a) should also be true. Just replace a andb with instance of Super class and Sub class, and you will end up breaking symmetry rule for equals() method.


How do you avoid NullPointerException, while comparing two Strings in Java?
Since when compared to null, equals return false and doesn't throwNullPointerException, you can use this property to avoid NPE while using comparing String. Suppose you have a known String "abc" and you are comparing with an unknown String variable str, then you should call equals as "abc".equals(str), this will not throw Exception in thread Main: java.lang.NullPointerException, even if str is null. On the other hand if you call str.equals("abc"), it will throw NPE. So be careful with this. By the way this is one of the Java coding best practices, which Java developer should follow, while using equals() method.


What is difference between "==" and equals() method in Java?
One of the most classical interview question on equals(). It has been asked numerous times during in past decade.


That's all on this list of Java interview Questions on Equals and HashCode methods in Java. It's one of the fundamental concept of Java programming language, but yet has several subtle things, which is unknown to many Java programmers. I strongly suggest to get yourself really good on equals(), hashCode(), compareTo() and compare()method, not only to do well on Java Interviews, but also to write correct code in Java.





Other posts you may like :




                                                                                  Javasourceworld                         A Java quick reference blog



Read More »

Java Source World: Serialization in Java

Serialization in Java | Java Source World

                                                           Javasourceworld                         A Java quick reference blog



Serialization in Java | Why we need to implement Serializable interface in java 


java.io.Serializable Interface :
This interface is used to mark serialization and deserialization of an object. Serialization is a process in which an object state is read from memory and written into a file or a database. Deserialization is a process in which an object state is read from a file or a database and written back into memory. Any class which wants it’s object to be eligible for serialization and deserialization must implement Serializable interface.

Why we need to implement Serializable interface:



Lets go through an example by the way we will understand why we need to implement Serializable interface in java.

For example I have a class Employee.java which is having properties and their getter and setter methods.

 Employee .java

package com.core.serialization;
import java.io.Serializable;

public class Employee implements Serializable{
                private int employeeID;
                private String firstName;
                private String lastName;
                 private static final long serialVersionUID = 1L;
                public int getEmployeeID() {
                                return employeeID;
                }
                public void setEmployeeID(int employeeID) {
                                this.employeeID = employeeID;
                }
                public String getFirstName() {
                                return firstName;
                }
                public void setFirstName(String firstName) {
                                this.firstName = firstName;
                }
                public String getLastName() {
                                return lastName;
                }
                public void setLastName(String lastName) {
                                this.lastName = lastName;
                }
}

Now I want to write the state of an Employee object to a file. To do that I need to use FileOutputStream and ObjectOutputStream to wrirte the state of an object to a file.

   SerializationClass.java

               package com.core.serialization;
               import java.io.FileNotFoundException;
                import java.io.FileOutputStream;
                import java.io.IOException;
                import java.io.ObjectOutputStream;

                public class SerializationClass {
                         public static void main(String[] args) {
                                            Employee emp = new Employee();
                                             emp.setEmployeeID(1);
                                                emp.setFirstName("First Name");
                                                emp.setLastName("Last Name");
                                               
                              try {
                                    FileOutputStream fout = new FileOutputStream("C:/Users/Desktop/employee.txt");
                                           try {
                                                         ObjectOutputStream oout = new ObjectOutputStream(fout);
                                                                                oout.writeObject(emp);
                                                                                oout.close();
                                                                                fout.close();
                                                              System.out.println("Serialization data is saved in employee.txt");
                                                                } catch (IOException e) {
                                                                                e.printStackTrace();
                                                                }
                                                } catch (FileNotFoundException e) {
                                                                e.getMessage();
                                                }
                                }
                }

Now we will check the output of the above code by running it.
Console: Serialization data is saved in employee.txt

Now we will try to deserialize the object, before that just modify the Employee.java, just add one another extra property to Employee.java and remove the implements Serializable.
Just assume added the fallowing property to the Employee.java and removed the implements keyword.
private String cityName;

Now we modified the object which is already serialized before deserializing it.

Now we will try to deserialize the object.

To do that we need to read the file using FileInputStream and ObjectInputStream needs be used to read the object.

 DeSerializationClass.java

                package com.core.serialization; 
                import java.io.FileInputStream;
                import java.io.FileNotFoundException;
                import java.io.IOException;
                import java.io.ObjectInputStream;

                public class DeSerializationClass {
                                public static void main(String[] args) {
                                                Employee emp = null;
                                                try {
FileInputStream fis = new FileInputStream("C:/Users/Desktop/employee.txt");
try {
    ObjectInputStream ois = new ObjectInputStream(fis);
           emp = (Employee)ois.readObject();
 System.out.println("Employee: "+emp.getEmployeeID()+"\n"+emp.getFirstName());
catch (IOException e) {
              e.printStackTrace();
catch (ClassNotFoundException e) {
                e.printStackTrace();
                }
catch (FileNotFoundException e) {
                  e.printStackTrace();
}
                                               
                                }
                }

Now we will run the above code and see the output.
Console:
Output:
java.io.InvalidClassException: com.core.serialization.Employee; com.core.serialization.Employee; class invalid for deserialization
                at java.io.ObjectStreamClass.checkDeserialize(Unknown Source)
                at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
                at java.io.ObjectInputStream.readObject0(Unknown Source)
                at java.io.ObjectInputStream.readObject(Unknown Source)
                at com.core.serialization.DeSerializationClass.main(DeSerializationClass.java:15)
Caused by: java.io.InvalidClassException: com.core.serialization.Employee; class invalid for deserialization
                at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
                at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
                at java.io.ObjectInputStream.readClassDesc(Unknown Source)
                ... 4 more


So, we got java.io.InvalidClassException, becauase the Employee object is got modified and not implemented the Serializable interface. 

Now we will add implement Serializable interface to the Employee.java and run the same program, then we will get the fallowing console output.
Output:
Employee: 1
First Name

Code is got executed and produced the output, hence to avoid class cast exceptions while deserializing and to maintain the state of an object we should implement Serializable itnerface.



Also read:
Join() Method in Multi Threading
Equals and Hashcode
What will happen if equals and hashcode not overridden
What are marker interfaces in java
Differences between Aggregation and Composition




                                                           Javasourceworld                         A Java quick reference blog

Read More »

Wednesday 26 October 2016

Java Source World: What Are Marker Interfaces In Java



What Are Marker Interfaces In Java


Marker interfaces:

 Marker interfaces in java are interfaces with no members declared in them. They are just an empty  interfaces used to mark or identify a special operation. For example, Cloneable interface is used to mark cloning operation and Serializable interface is used to mark serialization and deserialization of an object. Marker interfaces give instructions to JVM that classes implementing them will have special behavior and must be handled with care.

Marker interfaces don’t provide any functionality. In earlier versions of Java (Before Java 5), marker interfaces are used to provide metadata to the readers. With the introduction of annotations from Java 5, annotations are used more instead of marker interfaces to provide metadata . But, still many use marker interfaces to mark the special behavior of a class.

Java’s built-in Marker Interfaces :

These are some built-in marker interfaces in java which are used to mark some special behavior of a class.
1) java.lang.Cloneable Interface :

This interface is used to mark the cloning operation. An object of a class which implements Cloneable interface is eligible for field-by-field copying of an object.
2) java.io.Serializable Interface :
This interface is used to mark serialization and deserialization of an object. Serialization is a process in which an object state is read from memory and written into a file or a database. Deserialization is a process in which an object state is read from a file or a database and written back into memory. Any class which wants it’s object to be eligible for serialization and deserialization must implement Serializable interface.

Why we need to implement Serializable interface:

Lets go through an example by the way we will understand why we need to implement Serializable interface in java.

For example I have a class Employee.java which is having properties and their getter and setter methods.

 Employee .java
package com.core.serialization;

import java.io.Serializable;

public class Employee implements Serializable{
                private int employeeID;
                private String firstName;
                private String lastName;
                 private static final long serialVersionUID = 1L;
                public int getEmployeeID() {
                                return employeeID;
                }
                public void setEmployeeID(int employeeID) {
                                this.employeeID = employeeID;
                }
                public String getFirstName() {
                                return firstName;
                }
                public void setFirstName(String firstName) {
                                this.firstName = firstName;
                }
                public String getLastName() {
                                return lastName;
                }
                public void setLastName(String lastName) {
                                this.lastName = lastName;
                }
}

Now I want to write the state of an Employee object to a file. To do that I need to use FileOutputStream and ObjectOutputStream to wrirte the state of an object to a file.

SerializationClass.java

               package com.core.serialization;
               import java.io.FileNotFoundException;
                import java.io.FileOutputStream;
                import java.io.IOException;
                import java.io.ObjectOutputStream;

                public class SerializationClass {
                         public static void main(String[] args) {
                                            Employee emp = new Employee();
                                             emp.setEmployeeID(1);
                                                emp.setFirstName("First Name");
                                                emp.setLastName("Last Name");
                                               
                              try {
                                    FileOutputStream fout = new FileOutputStream("C:/Users/Desktop/employee.txt");
                                           try {
                                                         ObjectOutputStream oout = new ObjectOutputStream(fout);
                                                                                oout.writeObject(emp);
                                                                                oout.close();
                                                                                fout.close();
                                                              System.out.println("Serialization data is saved in employee.txt");
                                                                } catch (IOException e) {
                                                                                e.printStackTrace();
                                                                }
                                                } catch (FileNotFoundException e) {
                                                                e.getMessage();
                                                }
                                }
                }

Now we will check the output of the above code by running it.
Console: Serialization data is saved in employee.txt

Now we will try to deserialize the object, before that just modify the Employee.java, just add one another extra property to Employee.java and remove the implements Serializable.
Just assume added the fallowing property to the Employee.java and removed the implements keyword.
private String cityName;

Now we modified the object which is already serialized before deserializing it.

Now we will try to deserialize the object.

To do that we need to read the file using FileInputStream and ObjectInputStream needs be used to read the object.

 DeSerializationClass.java

                package com.core.serialization; 
                import java.io.FileInputStream;
                import java.io.FileNotFoundException;
                import java.io.IOException;
                import java.io.ObjectInputStream;

                public class DeSerializationClass {
                                public static void main(String[] args) {
                                                Employee emp = null;
                                                try {
FileInputStream fis = new FileInputStream("C:/Users/Desktop/employee.txt");
try {
    ObjectInputStream ois = new ObjectInputStream(fis);
           emp = (Employee)ois.readObject();
 System.out.println("Employee: "+emp.getEmployeeID()+"\n"+emp.getFirstName());
catch (IOException e) {
              e.printStackTrace();
catch (ClassNotFoundException e) {
                e.printStackTrace();
                }
catch (FileNotFoundException e) {
                  e.printStackTrace();
}
                                               
                                }
                }

Now we will run the above code and see the output.
Console:
Output:
java.io.InvalidClassException: com.core.serialization.Employee; com.core.serialization.Employee; class invalid for deserialization
                at java.io.ObjectStreamClass.checkDeserialize(Unknown Source)
                at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
                at java.io.ObjectInputStream.readObject0(Unknown Source)
                at java.io.ObjectInputStream.readObject(Unknown Source)
                at com.core.serialization.DeSerializationClass.main(DeSerializationClass.java:15)
Caused by: java.io.InvalidClassException: com.core.serialization.Employee; class invalid for deserialization
                at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
                at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
                at java.io.ObjectInputStream.readClassDesc(Unknown Source)
                ... 4 more


So, we got java.io.InvalidClassException, becauase the Employee object is got modified and not implemented the Serializable interface. 

Now we will add implement Serializable interface to the Employee.java and run the same program, then we will get the fallowing console output.
Output:
Employee: 1
First Name

Code is got executed and produced the output, hence to avoid class cast exceptions while deserializing and to maintain the state of an object we should implement Serializable itnerface.



Also read:
 Join() Method in Multi Threading
Serialization in java
Equals() and hascode() in java



                                                      Java Source World                         A Java quick reference blog




Read More »