Brain On Java

If you are able to express something you learnt in a simple manner, then you can be confident that you knew it well enough. This blog is an attempt by a learner to prove the above fact.

Sunday, April 4, 2010

How to make 2 Objects equal based on its state

In Object class equals method is present. Its default behavior is to do '==' comparision, i.e., to see if the same Object is being referred by two references.

Below is the definition of equals() in Object class
public boolean equals(Object paramObject){
return (this == paramObject);
}

Let's guess the output of following snippet :
String str = "test";
String str2 = "test";
boolean flag =str.equals(str2);
System.out.println("String EQUAL :"+flag);

Guessed it right...It returns true. But How Come ?


In String class, equals method is overridden. Below snippet is its sample definition in String Class
public boolean equals(Object paramObject){
if (this == paramObject) {
return true;
}
if (paramObject instanceof String) {
//code to check whether the value of the current object is same as paramObject or not
return true;
}
return false;
}

It returns true if
1) Two references of type String refers to Same object on heap or
2) Value of two String objects are equal, provided two String objects are created 
    without new operator
 
Supoose, we have a custom class 'Name' as below :

class Name{
private String firstName;
Name(String firstName){
  this.firstName = firstName;
}
public String getFirstName() {
 return firstName;
}
public void setFirstName(String firstName) {
 this.firstName = firstName;
}
}

Let's guess the output of following snippet :
Name name1 = new Name("test");
Name name2 = new Name("test");
boolean flag = name1.equals(name2);
System.out.println("Name EQUAL :"+flag);

Its false. On instantiation, jvm searches for equals() in Name Class, as it doesn't find, it searches it in its super class Object. Behavior of equals method's behavior in Object class is to do '==' comparision. As name1 and name2 refer to 2 different objects, it returns false.

Lets include the beolw sinppet in Name class :
@Override
public boolean equals(Object obj) {
Name name = (Name)obj;
return this.firstName.equals(name.getFirstName());
}
Now,equals() in Name class is called.Instance variable value of object name1 is checked against instance variable value of object name2. Instance variable determines the state of the Object. Hence it returns true.

To make 2 different instances equal based on its state, we need to override equals method.


Source Code can be downloaded @ TestEquals

Sunday, March 28, 2010

Open Closed Principle

A Design principle is a basic tool or technique that can be applied for designing or writing code to make that code more maintainable, flexible or extensible. Open Closed Principle is one of the Design Principle.

Definition :
          Classes should be open for extension and closed for modification

Ex : class FlyingObject()
       {
           fly()
           {
                  //common behavior for all flying objects
           }
        }

      class Bird extends FlyingObject
      {
           fly()
          {
               //use the common behavior from FlyingObject + specific flying behavior of the Bird
          }
       }

     class Aeroplane extends FlyingObject
     {
          fly()
          {
                 //use the common behavior from FlyingObject + specific flying behavior of the Aeroplane
          }
     }

  Here, fly() method in Class FlyingObject is closed for modification but open for extension through     inheritance in its subclasses.


OCP is all about allowing change, but doing it without any modification to existing code i.e., it lets you extend your working code, without changing that code.

OCP is about flexibility, and goes beyond just inheritance. Composition is another way to achieve it.

Inheritance is a simple example of OCP, but anytime your code is closed for modification but open for extension, you are using OCP.

Simple Scenario :
If you have a private method closed for modification but have a public method that invoked the private method, you are extending the behavior of the private methods, without changing them.

OCP is really a combination of encapsulation and abstraction. In the above example, common behavior for all flying objects is abstracted and placed in base class, thus locking the code up from modification. Behaviour for fly() in Bird class needs an extension from the common behavior and it differs from fly() behavior in Aeroplane. Thus by encapsulating what varies from what stays the same, you are allowing behavior extension in subclasses.

About Me

My photo
Hyderabad, Telangana , India
I may NOT be what my MIND thinks. I believe I am what my HEART feels. I am a drop in an ocean if ocean is the divinity. The moment drop merges into ocean, it loses its identity. So am I. Until then I am what I am, eagerly awaiting for the merger.