Thursday, February 4, 2016

Why constructors cannot be final, static and abstract?

Why constructors cannot be final, static and abstract?

public class FinalConstructor {

     abstract static final synchronized private FinalConstructor() {

     }
}

Constructors can’t be final because when we use final with methods , that means method can’t be override. Constructors by Java rules can’t be override anyways , so no point in making constructors as final.

Constructors can’t be static because constructors in java are used to instantiate object (in use with new keyword) whereas static keyword is used for class variables and not object.

Constructors can’t be abstract because when you set a method as ‘abstract’, it means method doesn't have any body and you want to implement it at another time in a child class, but the constructor is called implicitly when the new keyword is used so it can’t lack a body.

Facts to know about Constructors

·     Chain hierarchy of Constructor    By default every constructor call their parent class' no argument constructor in            first line e.g super().

·       Constructor is not inherited in Java
    This is an interesting but non obvious information about constructor. When you         create a child class in Java, it inherits member variables, non final and non static          methods but not constructors. They belong to the class they are declared.

·        Static initializer and instance initializer block is executed before constructor.
    If you don't know how a class is loaded and initialize, read this. Apparently static       initializer is executed at the time of class loading and instance initializer block of a    class is executed before constructor of that class, but only after successful execution    of constructor from super class. If your parent class constructor throw exception          then instance initialization block will not execute. 

Wednesday, February 3, 2016

To find second and first minimum element in an array

To find second and first minimum element in an array 

// Time Complexity : O(n) - Only 1 pass is required.
public class SecondMinimum {
      public static void main(String[] args) {

            int[] arr = new int[] { 34, 45, 21, 12, 54, 67, 15 };
            int first, second, arr_size = arr.length;

            /* There should be atleast two elements */
            if (arr_size < 2) {
                  System.out.println(" Invalid Input ");
                  return;
            }

            first = second = Integer.MAX_VALUE;
            for (int i = 0; i < arr_size; i++) {
                  /*If current element is smaller than first then update    both first and second*/
                  if (arr[i] < first) {
                        second = first;
                        first = arr[i];
                  }

                  /* If arr[i] is in between first and second then update second*/
                  else if (arr[i] < second && arr[i] != first)
                        second = arr[i];
            }
            if (second == Integer.MAX_VALUE)
                  System.out.println("There is no second" + "smallest element");
            else
                  System.out.println("The smallest element is " + first
                              + " and second Smallest" + " element is " + second);
      }
}

Immutable Class

Snippet of an Immutable Class

A class whose attributes remain same once after instantiation of that particular object.

/* 1- Make your class final, so that no other classes can extend it */
public final class StudentImmutableClass {

/* 2- Make all your fields final, so that they’re initialized only once inside the constructor and never modified afterwards */
    
     private final int rollNo;
     private final String name;
     private final Age age;

     /* 3- If the class holds a mutable object:
      * Inside the constructor, make sure to use a clone copy of the passed argument and never set your mutable field to the real  instance passed through constructor, this is to prevent the clients who pass the object from modifying it afterwards.
    
      * Make sure to always return a clone copy of the field and never return the real object instance
     */  
    
     public StudentImmutableClass(int rollNo, String name, Age age) {
          this.rollNo = rollNo;
          this.name = name;
          this.age = getClone(age);
     }

     Age getClone(Age age) {
          Age ageClone = new Age();
          ageClone.setDate(age.getDate());
          ageClone.setMonth(age.getMonth());
          ageClone.setYear(age.getYear());
          return ageClone;
     }

     /* 4- Don’t expose setter methods */
     /* When exposing methods which modify the state of the      class, you must always return a new instance of the class */
    
     public int getRollNo() {
          return rollNo;
     }

     public String getName() {
          return name;
     }

     public Age getAge() {
          return age;
     }
}

Muttable class - Age.java

public class Age {
     int date;
     int month;
     int year;

     public int getDate() {
          return date;
     }

     public void setDate(int date) {
          this.date = date;
     }

     public int getMonth() {
          return month;
     }

     public void setMonth(int month) {
          this.month = month;
     }

     public int getYear() {
          return year;
     }

     public void setYear(int year) {
          this.year = year;
     }

}

Client calling Immutable class

public class TestImmutableClass {

     public static void main(String[] args) {

          Age age = new Age();
          age.setDate(1);
          age.setMonth(1);
          age.setYear(1992);

          /* Make sure that constructor return a clone of muttable object and not actual object */
          StudentImmutableClass student = new StudentImmutableClass(1, "Alex", age);

          System.out.println("Alex age year before modification = " + student.getAge().getYear());
          age.setYear(1993);
          System.out.println("Alex age year after modification = " + student.getAge().getYear());
     }
}

References

http://programmergate.com/create-immutable-class-java/