Monday, 5 October 2015

Java Method Overriding Rules


1) The method argument list in overridden and overriding methods must be exactly same if they don’t match, you will end up with an overloaded method.

Method overriding exists only in sub class.

2) The return type should be the same or a subtype of the return type declared in the original overridden method in the super class.

3) private, static and final methods cannot be overridden.

4) An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not.

5) Overriding method cannot throw checked Exception higher in hierarchy than thrown by overridden method.

Example:parent class method throws FileNotFoundException, the overriding child class method can throw FileNotFoundException; but it is not allowed to throw IOException or Exception, because IOException or Exception are higher in hierarchy i.e. super classes of FileNotFoundException.

5) Overriding method cannot reduce the access scope of overridden method.

If overridden method in parent class is protected, then overriding method in child class cannot be private. It must be either protected (same access) or public (wider access).

6) A subclass in a different package can override the methods declared public or protected and default can override in same package.

7) Constructors cannot be overridden.

Factory Method Pattern (Virtual Constructor)

When we want to return one sub-class object from multiple sub-classes using an input, should use Factory design pattern. Factory class takes responsibility of instantiation the class (We can return Singleton instance from static factory method).

In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.



       

Example:Coffee/Vending machine, give input from options and as per input coffee, lemon tea, plain milk or hot water will be an output.

interface Drink {
       void prepare();
}

class Coffee implements Drink {
       @Override
       public void prepare() {
              System.out.println("Coffee is prepared !!");
       }
}

class LemonTea implements Drink {
       @Override
       public void prepare() {
              System.out.println("Lemon Tea is prepared !!");
       }
}

class PlainWater implements Drink {
       @Override
       public void prepare() {
              System.out.println("Plain Water is prepared !!");
       }
}

class VedingMachine {
       public static Drink getDrink(String str) {
              if("PlainWater".equals(str)) {
                     return new PlainWater();
              } else if("Coffee".equals(str)) {
                     return new Coffee();
              } else if("LemonTea".equals(str)) {
                     return new LemonTea();
              }
              return null;
       }
}

public class FactoryPatternTest {
       public static void main(String[] args) {
              Drink drink = VedingMachine.getDrink("Coffee");
              drink.prepare();
       }
}

Output: Coffee is prepared !!


Benefits of Factory Method Pattern

Factory Method Pattern provides approach to code for interface rather than implementation and it provides abstraction between implementation and client classes through inheritance.

Factory Method Pattern allows the sub-classes to choose the type of objects to create.

We can easily change the implementation of sub-class because client program is unaware of this. It makes code more robust, less coupled and easy to extend (client interacts solely with the resultant interface or abstract class).

Usage in JDK

java.util.Calendar, ResourceBundle and NumberFormat getInstance() methods uses Factory pattern.

valueOf() method in wrapper classes like Boolean, Integer etc.

Spring and hibernate frameworks.



Friday, 2 October 2015

instanceof Operator

The Type Comparison Operator instanceof

The instanceof operator compares an object to a specified type.

We generally use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

class Parent {

}

class Child extends Parent implements MyInterface {

}

interface MyInterface {

}

class InstanceofDemo {
      public static void main(String[] args) {
           Parent obj1 = new Parent();
           Parent obj2 = new Child();

           println("obj1 instanceof Parent: " + (obj1 instanceof Parent));
           println("obj1 instanceof Child: " + (obj1 instanceof Child));
           println("obj1 instanceof MyInterface: "+
                                         (obj1 instanceof MyInterface));
           println("obj2 instanceof Parent: "+ (obj2 instanceof Parent));
           println("obj2 instanceof Child: "+ (obj2 instanceof Child));
           println("obj2 instanceof MyInterface: "+
                                        (obj2 instanceof MyInterface));
     }
     static void println(String string) {
           System.out.println(string);
     }
}

Output:
obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true

Downcasting with java instanceof operator

When Subclass type refers to the object of Parent class, it is known as downcasting.

If we perform it directly, compiler gives Compilation error.

If you perform it by typecasting, ClassCastException is thrown at runtime. But if we use instanceofoperator, down casting is possible.

class Parent1 {

}

class Child1 extends Parent1 {
       static void method(Parent1 obj) { 
              if(obj instanceof Child1){ 
                     Child1 obj1 = (Child1)obj; //downcasting 
                     System.out.println("downcasting successfully !!"); 
              } 
       }
}

class DownCasting {
       public static void main(String[] args) {

              Parent1 obj=new Child1();
              Child1.method(obj);
       }
}
Output:
downcasting successfully !!

If we apply the instanceof operator with any variable that has null value, it returns false.

Prefer polymorphism over instanceof and downcasting.
Related Posts Plugin for WordPress, Blogger...