Monday, October 22, 2012

What are the differences between Interface and Abstract class?

Abstract Classs
Intrerface
 A class may extend only one abstract class.
A Class may implement several interfaces.
An abstract class can have non-abstract methods.
All methods of an Interface are abstract.
An abstract class can have instance variables.
An Interface cannot have instance variables.
An abstract class can have any visibility: public, private, protected.
An Interface visibility must be public (or) none.
An abstract class can contain constructors.
An Interface cannot contain constructors.
An abstract class can provide complete, default code and/or just the details that have to be overridden.
An interface cannot provide any code at all, just the signature. (I.e. All Interface methods are public).
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.

Friday, October 19, 2012

Creational Design Pattern : Abstract Factory


Abstract Factory is a creational design pattern and it provides one level of interface higher than the Factory design pattern.
Problem:
To create complex objects, we use the factory method but it provides same class object for that method.
Solution:
We provide one extra interface to switch the factory.
Implementation:
Button.java:
public interface Button {
      public void click();
}
Xbutton.java:
public class XButton implements Button {
      @Override
      public void click() {
            System.out.println("XButton is clicked.");
      }
}
Ybutton.java:
public class YButton implements Button {
      @Override
      public void click() {
            System.out.println("YButton is clicked.");
      }
}
ButtonFactory.java:
public interface ButtonFactory {
      public Button createButton();
}
XButtonFactory.java:
public class XButtonFactory implements ButtonFactory {
      @Override
      public Button createButton() {     
            return new XButton();
      }
}
YButtonFactory.java:
public class YButtonFactory implements ButtonFactory{
      @Override
      public Button createButton() {
            return new YButton();
      }
}
Test.java:
public class Test {
      public static void main(String[] args) {
        ButtonFactory factory = new XButtonFactory();
        Button button = factory.createButton();
        button.click();
        factory = new YButtonFactory();
        button = factory.createButton();
        button.click();
    }
}

Wednesday, October 10, 2012

Design Pattern: NullObject


Null Object Pattern is one of good pattern used to avoid NullPointerException.
Null Object is not ‘null’ i.e. it is not default value used for object references.

Problem:
We use the null condtion to check the value is null or not null to avoid Null Pointer Exception But it is not a proper solution because we need to add this check whereever we call a method on our object.
I.e. we need to null check for each object before making the calls finally, unnecessary code and unnecessary checks will be added in our program.

Solution:
Create an object that will do nothing whenever nothing is available for reference.

Let’s see the implementation:

Animal:
public interface Animal {
    public void makeSound();
}

Dog: Actual Animal
public class Dog implements Animal {
    public void makeSound() {
            System.out.println("woof!");
    }
}

NullAnimal: Default Animal
public class NullAnimal implements Animal {
    public void makeSound() {
    }
}

When we know actual animal then we will create that animal class if not applicable we will create NullAnimal with default and it will not do anything.

Cohesion and Coupling


Cohesion and Coupling deal with the quality of an Obeject Oriented design. Generally, good OO design should be loosely coupled and highly cohesive. Lot of the design principles, design patterns which have been created are based on the idea of “Loose coupling and high cohesion”.
The aim of the design should be to make the application:
  • easier to develop
  • easier to maintain
  • easier to add new features
  • less Fragile.
Coupling:
Coupling is the degree to which one class knows about another class. Let us consider two classes class A and class B. If class A knows class B through its interface only i.e it interacts with class B through its API then class A and class B are said to be loosely coupled.
If on the other hand class A apart from interacting class B by means of its interface also interacts through the non-interface stuff of class B then they are said to be tightly coupled. Suppose the developer changes the class B‘s non-interface part i.e non API stuff then in case of loose coupling class A does not breakdown but tight coupling causes the class A to break.
So its always a good OO design principle to use loose coupling between the classes i.e all interactions between the objects in OO system should use the APIs. An aspect of good class and API design is that classes should be well encapsulated.
Cohesion:
Cohesion is used to indicate the degree to which a class has a single, well-focused purpose. Coupling is all about how classes interact with each other, on the other hand cohesion focuses on how single class is designed. Higher the cohesiveness of the class better is the OO design.
Benefits of Higher Cohesion:
  • Highly cohesive classes are much easier to maintain and less frequently changed.
  • Such classes are more usable than others as they are designed with a well-focused purpose.
Single Responsibility principle aims at creating highly cohesive classes.

Thursday, October 4, 2012

UML Relations : Association, Aggregation, Composition, Dependency, Realization, Abstraction and Generalization.



We use some key terms to specify the relationship between objects. Those are Association, Aggregation, Composition, Dependency, Realization, Abstraction and Generalization. I have tried to put the relations in following chart as per their definations to remember easily.


Association
An Association is the basic term to represent the relation between objects and we can say it is parent of any relation between objects.

Aggregation
Aggregation is more specific than Association. It is a variant of the "has a" or association relationship; I.e. when an object holds other object then we called it as Aggregation.
Eg:
public class Library {
      private Student student;

      public Student getStudent() {
            return student;
      }

      public void setStudent(Student student) {
            this.student = student;
      }    
}

Composition
Composition is more specific than aggregation. It is a stronger variant of the "owns a" or association relationship i.e. contains object will not exists without the container class.
Eg:
public class Library {
      private Book book;

      public Book getBook() {
            return book;
      }

      public void setBook(Book book) {
            this.book = book;
      }    
}
There will be no book without library.

Dependency
Dependency is more specific than Composition. It is a weaker form of relationship which indicates that one class depends on another because it uses it at some point of time. I.e. One class depends on another.
public class Circle {
      public void calulateArea(Util util){
            util.area();
      }
}
Util is not useful without Circle and Circle will not provide calculateArea without Util.

Multiplicity
Multiplicity is more specific than Composition. This is association relationship indicates that (at least) one of the two related classes makes reference to the other. I.e. one contains other and vice-versa.
One:
public class One {
      private Two two;

      public Two getTwo() {
            return two;
      }

      public void setTwo(Two two) {
            this.two = two;
      }
     
}
Two:
public class Two {
      private One one;

      public One getOne() {
            return one;
      }

      public void setOne(One one) {
            this.one = one;
      }
     
}

Abstraction
Abstraction is an association used to hide the low level implementation. I.e. Considering the Category of the object is an abstraction.
Eg:
public interface Vehicle {
      public void forward ();
      public void reverse ();
      public void right ();
      public void left ();
}

Realization
A realization relationship between classes and interfaces and between components and interfaces shows that the class realizes the operations offered by the interface.
Eg:
public abstract class Car implements Vehicle{
      public void forward(){}
      public void reverse(){}
      public void right(){}
      public void left(){}   
}

Generalization:
Generalization uses a “is-a” relationship from a specialization to the generalization class. Common structure and behavior are used from the specialization to the generalized class.
Eg.
public class GenericCar extends Car{

      @Override
      public void forward() {      
            System.out.println("move forwad.");
      }

      @Override
      public void reverse() {
            System.out.println("move reverse.");
      }

      @Override
      public void right() {
            System.out.println("move right.");
           
      }

      @Override
      public void left() {
            System.out.println("move left.");
      }
}

Java Class Loader


Classloader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. It is an object that is responsible for loading classes. The class java.lang.ClassLoader is an abstract class. Given the binary name of a class, a class loader should attempt to locate or generate data that constitutes a definition for the class. A typical strategy is to transform the name into a file name and then read a "class file" of that name from a file system.
The following picture illustrates the hierarchy of class loaders. Root loader is bootstrap class loader which has native implementation and cannot be instantiated by Java code.


The class loaders in Java are organized in a tree. Class loader determines the class looking up in cache, paret and self in order.
However, some classes may not originate from a file; they may originate from other sources, such as the network, or they could be constructed by an application. The method defineClass converts an array of bytes into an instance of class Class. Instances of this newly defined class can be created using Class.newInstance.
The methods and constructors of objects created by a class loader may reference other classes. To determine the class(es) referred to, the Java virtual machine invokes the loadClass method of the class loader that originally created the class.
For example, an application could create a network class loader to download class files from a server. Sample code might look like:
   ClassLoader loader = new NetworkClassLoader(host, port);
   Object main = loader.loadClass("Main", true).newInstance();
          . . .

The network class loader subclass must define the methods findClass and loadClassData to load a class from the network. Once it has downloaded the bytes that make up the class, it should use the method defineClass to create a class instance. A sample implementation is:
public class NetworkClassLoader extends ClassLoader {
    String host;
    int port;

    public Class findClass(String name) {
        byte[] b = loadClassData(name);
        return defineClass(name, b, 0, b.length);
    }

    private byte[] loadClassData(String name) {
        // load the class data from the connection
      byte[] b = null;
      //...
      return b;
    }
}

Any class name provided as a String parameter to methods in ClassLoader must be a binary name as defined by the Java Language Specification.
Examples of valid class names include:
   "java.lang.String"
   "javax.swing.JSpinner$DefaultEditor"
   "java.security.KeyStore$Builder$FileBuilder$1"
   "java.net.URLClassLoader$3$1"