Friday, September 19, 2014

Constructor inheritance(ovveriding) and reasons behind restricting constructor inheritance in Java.

Inheritance is one the key concept of OOP. Being object oriented language, Java supports it. With inheritance every Child becomes a Parent. You can access the properties of Parent from a Child once you inherit Parent (using extends keyword). Here is a key point to note that, though you can access the members of Parent you cannot inherit/ or override constructor in Java. In this article let us discuss the reasons behind restricting Constructor Inheritance.
  • With inheritance you can access only Class members from Parent. Since constructor is not a class member, hence you cannot inherit from Parent. In a class, class members are only Fields, Methods and Nested classes.
  • Another possible reason to restrict constructor inheritance is that as we discussed in the article about constructor constructor must be the Class's simple name. If you inherit your parent constructor, then the rule breaks as Child and Parent have a different Class names.
  • And also consider Parent class have a no argument constructor and when you inherit that Parent, in case of Child you cannot provide Child's own default constructor which with a private access modifier. So making your Child class constructor private (downgrading the access) is a dream if there is constructor inheritance.

By observing the above points, it makes sense that there are good amount of reasons to stop overriding/inheriting the constructor of Parent. That is not finishes the story. Still you can use or invoke the super class constructor.

Invoking super class constructor :

Though you cannot use inheritance with constructor are free to invoke Parent class constructor with help of super keyword from Child
(super(), super(args)).

If we are saying constructor inheritance is not possible, that doesn't mean that you cannot communicate between parent class constructor and child constructors. There can be a clean communication between the constructors using super keyword.
ChildClassConstructor(){  
   super(param_needed); //Invoking super class constructor with params  
 }  
 ChildClassConstructor(){  
   super(); //Invoking super class default constructor.  
 }  
Like the way shown in above you can invoke any super class constructor using super. That is all about invoking Parent class constructor and what happens when you are not explicitly invoking any super class constructor (for your needs)?? Though you are not invoking Invoking a super class constructor doesn't mean that you are executing only Child class constructor alone. There is a interesting fact that your super class constructors(till n'th super class, which is Object class constructor) also calls in that process(shown below in code). you can observe when you invoke any Child constructor. There is a chain call to the immediate parent class constructor from the current class. And the call continues until the Object class constructor invokes since that the possible most Parent classes super class is. For ex:
 public class ParentClass {  
      public ParentClass() {  
           System.out.println("Parent default constructor invoked");  
      }  
      public ParentClass(int a) {  
           System.out.println("Parent argumented constructor invoked");  
      }  
      public static void main(String[] args) {  
           SubSubClass sub = new SubSubClass();  
      }  
 }  
 class SubClass extends ParentClass {  
      public SubClass() {// not calling any super  
           System.out.println("Child default constructor invoked");  
      }  
      public SubClass(int b) {  
           super(b);  
           System.out.println("Child default constructor invoked");  
      }  
 }  
 class SubSubClass extends SubClass {  
      public SubSubClass() {// not calling any super  
           System.out.println("Sub Child default constructor invoked");  
      }  
      public SubSubClass(int b) {  
           super(b);  
           System.out.println("Sub Child default constructor invoked");  
      }  
 }  
 OUTPUT:  
 Parent default constructor invoked  
 Child default constructor invoked  
 Sub Child default constructor invoked

As you are seeing that we are not calling any super class constructor, still we can see the calling hierarchy of Constructor calling till the most possible super class which Object class's constructor and returns to the current (Child) class's constructor business logic. Summarizing the points to remember below.
  • If you call any specific super constructor (super or super(args)), then that specific super constructor invokes.
  • If you are not calling any specific constructor, then default super constructor(super()) invokes.
  • When you invoke any specific (super(args)) parent constructor that only executes and default constructor of Parent wont get execute.

Constructor overloading and constructor chaining in Java

Whenever people just say constructor is just like a method, I'm really scared about their understanding and I really pity on constructor. The concept of constructor is completely different from a normal method. When we actually want to dig in to the core concepts, one of the key point to learn is about constructor which is used to initialize the class properties (or any other initial business logic after initialization of properties) while object creation.

What exactly we have to say is it looks like just a method but which is entirely a different thing and lot of things happen under the hood when you invoke constructor. To create an instance we must need a constructor for every Java Class. A good point to remember here is, a constructor never return anything.
JavaConstructor jCInstance = new JavaConstructor(); 
If you see the above line of code JavaConstructor is the class name and JavaConstructor() is the constructor of it. 
class JavaConstructor{  
   JavaConstructor() {   //default or no argument constructor
   //do something   
   }  
 }  
To be valid the class declaration of JavaConstructor must be the simple name of the class. Here in the above declaration I left the access modifier as default for the constructor.

 Argumented Constructor:-

An argumented constructor is which used to pass required information to the class while creating an object. Below example demonstrates that how Bus class is forcing the consumers to pass the number of seats  while creating a Bus.
Class Bus{   
  int seats;  
   Bus(int seats) {  // argumented constructor  
   this.seats = seats;  
   //do something    
   }   
  }  
Now whom so ever want to create a Bus, they can pass the no.of seats required to the Bus class. Just for example I took seats. Depends on the requirement's the arguments list may vary(color,length etc ..).
Bus volvoBus = new Bus(34); //passing seat count
Bus ordinaryBus = new Bus(28); //passing seat count

The points to note here are
  • If you forgot to write or not intentionally writing a constructor to your class, JVM creates a one for you internallywhich is a default no argument constructor.
  • If you provide a default (no arg) constructor, JVM uses it to instantiate.
  • If you are not providing default constructor and providing a argumented constructor, then consumers definitely needs to pass the required parameters. In this case, consumers cannot use default constructor anymore since you provided a argumented one and not providing default on while creating object. If they try to use default one compiler error occurs. 
Constructor Overloading:-

Just like method overloading in Java, there is constructor overloading too. Overloading a constructor means providing multiple constructors differing in arguments for a Class. For ex:
public class Bus {  
      int noOfSeats;  
      String busColor;  
      public Bus() {  
           System.out.println("This is default constructor");  
      }  
      public Bus(int seats) {  
         this.noOfSeats = seats;  
           System.out.println("To call this constructor, you need need to pass no of seats");  
      }  
      public Bus(int seats, String color) {  
         this.noOfSeats = seats;  
         this.busColor = color;  
           System.out.println("To call this constructor, you need to pass bus color");  
      }  
 }  
If you see there are multiple constructors provided with different arguments. We just overloaded the constructor. When we want to create a required bus we have to just use the appropriate constructor. It's up to us to create/passing info while creating a bus. You may buy a bus with 20 seats and color it later. Creating different types of buses is possible with above provided constructors.
class BusCreator {  
      public static void main(String[] args) {  
           Bus bus = new Bus();// I just need a bus'  
           Bus seatsBus = new Bus(20);// I need a bus with 20 seats  
           Bus coloredBus = new Bus(25, "Blue");// Need a blue color bus with 20 seats.  
      }  
 }  

Constructor Chaining-

Like the confusion between method and constructor, few usually state that invoking Parent class constructor from Child is constructor chaining. No. That is not 100% true. Weather it is own constructor or Parent constructor, invoking one constructor from other can state as constructor chaining. Lets see the below examples how usually chaining the constructor happens with in the same class and with Parent class.


We chain(calling) one constructor from other with in the same classso that we can avoid code duplication. Without chaining every constructor have whole business logic and that leads to code duplication and hard to maintain the code as well.
public class Bus {  
      int noOfSeats;  
      String busColor;  
      public Bus() {  
           constructBus();  
      }  
      public Bus(int seats) {  
           this();// calling default constructor for business logic.  
           this.noOfSeats = seats;  
      }  
      public Bus(int seats, String color) {  
           this(seats); // Using another constructor and proceeding..  
           this.busColor = color;  
      }  
      private void constructBus() {  
           // Whole process of constructing bus.  
      }  
 }  
Below we chained Parent constructor to Child constructor as below to pass the required information to Parent while creating a Child object.
public class Vehicle {  
      private String vehicleName;  
      public Vehicle(String name) {  
           this.vehicleName = name;  
      }  
 }  
 class Bus extends Vehicle {  
      int noOfSeats;  
      String busColor;  
      public Bus() {  
           super("bus"); // calling super constructor.  
           constructBus();  
      }  
 }  

Tuesday, September 16, 2014

Print preview images and css not loading for first time.

While I'm trying to print one of my web pages in browser, faced a strange issue today. When I click the print button for the first time, the print preview (in chrome browser) looks like weird and no images and styles are appeared in the print preview. Where as if I click again, strangely everything is fine.

The reason is that, there is a slight difference between, loading the images,css files and the print preview. The print preview winning the race and the images and css files loading later. So when I click next time the already loaded images and css files are showing up in the print preview and everything fine.

The solution is that with help of a timer/timeout we need to wait until the css and image load. So that the images and css files load in that interval before showing up the preview. In GWT case the code looks alike

public static void printHTML(String html) {  
           try {  
                Timer timer = new Timer() {  
                     public void run() {  
                          yourPrintGoesHereWithHtml(html);  
                     }  
                };  
                timer.schedule(TIMER_DELAY * 1000);// TIMER_DELAY= 1 or 2 (based on net speed)  
           } catch (Throwable exc) {  
                Window.alert(exc.getMessage());  
           }  
      }  
Javascript solution:

The same solution applies for JavaScript as well. Instead of timer we can use setTimeOut method here.
setTimeout(function(){  
    //Your Print Function goes here  
  }, 3000); //giving 3 sec loading time. May vary.
That way we can wait to load the css and image files by browser and the print preview functionality can proceed without any problems.

Note: After so much goggling only I went for this solution. If anyone know a better idea to overcome this problem, please comment. It would be great if anyone come up with a solution without a timer.

Monday, September 15, 2014

Why to use UIBinder in GWT

One of my favorite feature released in GWT 2.4 is Declarative Layout aka UiBinder, a quick way to design the UI. The biggest advantage of using it is to separate the UI declaration from sensitive Java code. When the release team introducing UiBinder, they stated as below
UiBinders provide a way for you to declare the layout of your application and widgets using traditional HTML and CSS rather than programatically in java. This provides you with a much richer way to create your application.

Browsers are better at building DOM structures by cramming big strings of HTML into innerHTML attributes than by a **bunch of API calls**. 
UiBinder 
naturally takes advantage of this, and the result is that the most pleasant way to build your app is also the best way to build it.

The UiBinder is a framework designed to separate Functionality and View of User Interface. It allows developers to build gwt applications as HTML pages with GWT widgets configured throughout them.
More over it makes easier collaboration with UI designers who are more comfortable with XML, HTML and CSS than Java source code.

As a Java developer I came across the old school days JSP and HTML as well and from that experience and after I move to GWT technology what I can say is The UIBinder is similar to what JSP is for Servlets.


The summary of the above all is (from my development experience):


1. If you are familiar with HTMl, and CSS,you can simply layout the structure there(means in ui.xml templates)and can simply play with GWT. This reduces your compile time.


2. Again, You can simply write the markup in xml and apply styles and other DOM attributes,where as in java code you have to write no.of lines of code [well at least 2 to 3] prepare a widget with styles and specific DOM attributes.


If you want to get started with it, Here I found a good
 example that how UiBinder gives advantage over the traditional java code.

I hope others will also share their experience  here about UiBinder usage.

Friday, September 5, 2014

Default access modifier in Java (or) No access modifier in Java

When we do programming, one of the key points to remember is providing access control to the attributes you are writing. Otherwise you cannot make sure, which is going to be change and which attribute you can have control to write the flow of your algorithm. 
 public class Account{   
  public long amount= 100;   
  } 
If you see the above variable amount, you can access anywhere either with in the class, sub classes, even in other packages if you have an instance of Account in your hand. You have no clue who is modifying your money and you cannot have much control on it. See in below case
 public class Account{   
  protected long amount= 100;   
  } 
If it is protected, this is a kind of protected state (in a shell), where only with in the class and sub classes can access (SavingsAccount,CurrentAccount etc ..) and for with in the package which is the class present can access it. With in the package means the package that Account class presented.
public class Account{   
  private long amount= 100;   
  } 
Where as in case of private, it is strictly accessible only in the current class. No one see the variable out side from class. If anyone still want to expose the private variables value, provide a getter and return the value where there is no way to access the variable outside from the class.
 public class AccessDemo {   
  int instanceCount= 1;   
  }  
So, what if one didn't specify the access modifier ?? Compiler treats that as a default modifier aka no modifier. When there is no modifier specify to any of the members in a class, compiler treats that member as a default accessible type member. A default accessible type member is Package Private member. Only with in the Class and with in the Package only you can access that default member. But It is always recommended to specify the access specifier. 

Oracle draw a table in their docs to understand easily and to refer them quickly.
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
The above table copyright belongs to Oracle.