Tuesday, January 13, 2015

Constructor Chaining with example.

What is Constructor chaining?
Executing current class constructor and super class constructor up to the object class no argument constructor is called the constructor chaining.

Hard and Fast rule for constructor chaining.

Rule no 1:-If no constructor is defined, compiler will define it for you, which is the default constructor, and the first call in the default constructor is the call to the super ().

Rule no 2:-If you have your own constructor, then compile will see if ‘this()’ is being called or not,if this() is not called, it will insert the super() as the first call.

These 2 two points are sufficient to understand constructor chaining. :-) if you understood these rules you have win the half battle.

Consider the following example.

class Person {
int id = 10;
String name;

Person(int i) {
System.out.println("person"+i);
   }
}

class Employee extends Person{
Employee(){
  }
}

public class Constructer {

public static void main(String[] args) {
Person p = new Person(10);
}
}

What do you think, will it compile successfully.Lets apply the two rules.
Start from the Employee class.

Observation 1.Employee class does have a no-arg constructor defined,the compiler will next see if this constructor has a this() call, no then will put a super();

Employee()
{
super();
}

Observation 2.because of super() call, it will go to the Person class and looks for the no argument constructor in Person class but the person class does not have a no-arg constructor in it,as a result gives a compile time error.

Below code will compile successfully.

class Person {
int id = 10;
String name;
Person(){
     }
Person(int i){
System.out.println("person"+i);
           }
}

class Employee extends Person{
Employee(){
}
                                        }

public class Constructor {
public static void main(String[] args) {
Person p = new Person(10);
}
}
******************************************************************************************************
Example 2.

class Person {
int id = 10;
String name;

Person(int i){
System.out.println("person"+i);
         }
}

class Employee extends Person{
int i = 200;
double  salary;

Employee(int i){
super(i);
System.out.println("Employee");
}

}

public class Test {
public static void main(String[] args) {
Person p = new Employee(10);
}

}

Observation 1.Employee Class has a constructor which takes int as an argument ,compiler checks if it has call to this() or super(),and finds that super(i) is present.

Employee(int i){
super(i);
System.out.println("Employee");
}


Observation 2.because of super(i), it goes to its parent class which is Person class and search for a constructor which takes an int as an argument,an find one.
Person(int i){
System.out.println("person"+i);
}

Again compiler check if in the Person(int i) constructor, this() is present says NO,so compiler then inserts the super(),because of which it will go to the object class.

Result complies successfully.

******************************************************************************************************
Example 3.

class Person
{
int id = 10;
String name;

Person(int i){
System.out.println("person with arg constructor");
}
{
System.out.println("person initilization block");
}

Person(){
this(10);
System.out.println("person no arg constructor");
}
}

class Employee extends Person{
Employee(int i){
System.out.println("Employee with arg constructor");
}
{
System.out.println("Employee initilization block");
}
Employee(){
this(10);
System.out.println("Employee no arg constructor");
}

}

public class Test {
public static void main(String[] args) {
 new Person();
 new Employee();
}
}


Note:-In constructor chaining,  initialization block executes only when the control returns back from the super class constructor.

Observation 1." new Person();":-Call the Person Class no arg constructor,sees if it has this() or super() call.
Observation 2. finds this(10),looks in the person class for a constructor which accepts int as a argument, and find,

Person(int i){
System.out.println("person with arg constructor");
}
again look for this() or super(), but its not there ,so it insert super(),as follows

 Person(int i){
        super();
System.out.println("person with arg constructor");
}
goes to the object class,since Person class by default extends Object class,when control return from the object class to the Peron class it will execute the initialization block,then the Person(int i) constructor then Person() constructor .
The output will be as follows "person initialization block"---->"person with arg constructor"--->"person with arg constructor"

Observation 3
new Employee() calls the Employee class no argument constructor.

Employee(){
this(10);
System.out.println("Employee no arg constructor");
}
Encounter "this(10)",search for the constructor in the Employee Class which takes int as an argument.
And find the following code.

Employee(int i){
System.out.println("Employee with arg constructor");
}

sees if "this()" is there,say NO so compiler will insert the "super()". OK,on seeing super() compiler looks for the parent class of the Employee, which has a no argument constructor, as a result goes to the following constructor.

Person(){
this(10);
System.out.println("person no arg constructor");
}

Compiler sees the "this(10)" as a result does not insert "super()". super()  will come only when this() is not there. this(10) will make a call to the constructor in Person class which takes int as an argument,and find the following snippet.

Person(int i){
System.out.println("person with arg constructor");
}

Again the compiler will see if this() is present in the constructor,say no so insert super(),super()  will call the object class constructor, on returning from the object class it will execute the initialization block code,then the Person(int i) constructor and the Person() constructor,then Employee initilization block, then Employee(int i) code and finally Employee() code .
******************************************************************************************************

Understanding why java does not support multiple inheritance.

Lets see the code first.

class Employee {
 }
 class Student {
 }

class Person extends Student,Person{
Person()
        {
super();   //ambiguity arises where to go Student  or Employee
}
}
******************************************************************************************************






Method OverLaoding and OverRiding.

This is once of the most simple topic in java,however a lot of people does not have a clear understanding of method overloading and overriding.After reading this post you will have a sound knowledge of the above concept.

First i will start with Method Overriding.

Method overriding will be initiated only when super class inherited method and subclass method has the same name and same list of argument.
We will take once simple example to understand the concept, i personally think that one example is sufficient to understand the concept.

Overriding has mainly two concept involved.
1. Static bound.
2 .Run time bound.
I will explain them in detail don't worry. :-)

First see the  code.

class Person {
int id = 10;
public void test() {
System.out.println("Test:Person");
}

}

class Employee extends Person {
int id = 20;
public void test() {
System.out.println("Test:Employee");
}
}


public class OverridingDemo {
public static void main(String[] args) {
Person p = new Employee();
p.test();
System.out.println(p.id);
}
}

output:-
Test:Employee
10

Person p = new Employee();
p.test();

During Compile time compiler will check test() method in Person class,because compile time will only check the data type of the reference variable, not the object stored in the reference variable.

So during compile time p.test() will link to the Person class text() method, This is called the STATIC BOUND.

During run time, run-time environment will again see if the test() method is overridden in any of the subclass or not, if it is overridden in any of the subclass, run-time will break the previously established STATIC BOUND and establish a new RUN TIME BOUND.  



as in the above code, p.test() will be linked to the Person class text() method during compile time,run time will again check if the test() method is overridden in the Employee class, if yes then calls the Employee class test() method by breaking the static bound.

so p.test() will call the different test() method depending upon whether is has been overridden or not this is nothing but polymorphic behaviour.

Please Note only method can be overridden not the instance variable.
p.id will still call the id of the Person class.


Method Overloading
Method overloading depends on the signature,and signature depends on 3 things
1. Number of argument.
2. Data type of argument.
3. Order of argument.

One point to remember is that Method Overloading does not depend upon the return types, will give compile time error.

public class Demo{

public static void main(String[] args) {
int i= calculateIntrest(0);
}

static int calculateIntrest(int r){
System.out.println("one");
}

static void calculateIntrest(int p){
System.out.println("two");
}
}

will be a compile time error because of  duplicate method,

What will be the output of the following code.

public class Demo{

public static void main(String[] args)
{
int i= calculateIntrest(0);   //int
}

static int calculateIntrest(double r)   //double
{
System.out.println("one");
return 10;
}

static int calculateIntrest(long p)   //long
{
System.out.println("two");
return 20;
}

}

output:- two

compiler will consider 0 as int and look for the match in following sequence .
int-->long-->float-->double 
long is before double, so it will execute the calculateIntrest which takes "long as a parameter".



Starting and Stoping FitNesse from java code

Indeed a lot of things have changed in the FitNesse code. A lot of fields have been made final, so it’s easier to reason about the code.

To create a context configuration we can use the fitnesse.ContextConfigurator class. It can be used to build a FitNesseContext to your liking, while the FitNesseContext fields remain final.

The ContextConfigurator is using a builder pattern, so you can configure it using the withXxx() methods

public void start() throws Exception {
try {
try {
if (fitnesse == null) {
FitNesseContext context = loadContext();
fitnesse = new FitNesse(context);
}
} catch (Exception e) {
throw e;
}
if (fitnesse != null) {
fitnesse.start();
}
} catch (RuntimeException e1) {
throw e1;
}

}

public void stop() throws Exception {
if (fitnesse != null) {
fitnesse.stop();
fitnesse = null;
}
}

protected FitNesseContext loadContext() throws Exception {
ContextConfigurator configurator = ContextConfigurator.empty();
   configurator.withParameter(ConfigurationParameter.ROOT_PATH,C:\\FitNesseRootPath);
 configurator.withParameter(ConfigurationParameter.PORT,8080);  
 configurator.withParameter(ConfigurationParameter.CONTEXT_ROOT, "/");

 FitNesseContext context = configurator.makeFitNesseContext();
return context;
}

java-8-streams-map-examples

package com.mkyong.java8; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; im...