Tuesday 21 June 2011

Java Instance Initialiser

I have almost always taken the Java object creation process for granted, mainly because there is nothing much to do for me and if I write my constructor properly, it will do it. When I have an integer field, let's say pages in a class called Book, I never cared to see if explicitly initialising this with a value such as 0 makes any sense in my constructed object since the default integer (when used primitive int) itself is 0. It may not be good as an example but something similar in an age old code made me to realise that though the values are the same, since the explicit initialisation of a field happens after the object construction in the parent classes, they could produce different results.

The following simple code would probably make you to think a while whether it would print 0 or 100.


public abstract class Book {
 public Book() {
  setPages(100);
 }
 public abstract void setPages(int pages);
 public abstract int getPages();
}

public class MyBook extends Book {
 private int pages = 0;

 public void setPages(int pages) {
  this.pages = pages;
 }

 public int getPages() {
  return pages;
 }

 public static void main(String[] args) {
  Book myBook = new MyBook();
  System.out.println(myBook.getPages());
 }
}

It may be obvious for some but the point is that why not 100? Simply because the initialisation of a field happens after the construction of parent objects and prior to the code within it's own constructor, whatever value the field got to have during the parent objects construction is simply vanished. I think it is more of a philosophy of a language based on it's principles than any hard and fast rules. For instance, the same piece of code in C# which is considered to be a close one to Java in many ways would behave just the opposite.

No comments:

Post a Comment