Sunday, September 28, 2014

how to show Order derivation using program in java?


If a Sub Class extends a Super Class then Super class Default constructor would be call first and then Sub class Default constructor will be called.  If sub class calling its own Parameterized constructor and if super keyword is not available (i:e; super(parameter)) in Parameterized constructor of  sub class then Default constructor of Super class call first and then Sub class parameterized constructor will be call.

NOTE:-
To call Super class parameterized constructor from sub class parameterized constructor, must use ‘super(parameter)’ statement in Parameterized constructor of sub class, otherwise it will call super class Default constructor first and then call sub class parameterized constructor.


Ex:
SuperClass.java

public class SuperClass
{
private String s="string of superclass";
publicSuperClass()
 {
System.out.println("Super class Default Constructor");
  }

publicSuperClass(String s)
 {
this.s=s;
System.out.println("Super class parameterized Constructor");
  }
} // Close of class Super class
SubClass.java
class SubClass extends SuperClass
{
 String sub="string of subclass";
SubClass()
 {
System.out.println("Sub class Default Constructor");
  }

SubClass(String sub)
 {
super("Avnish"); 
this.sub=sub;
System.out.println("Sub class parameterized Constructor");
  }

public static void main(String[] arg)
 {
SubClasssubobj=new SubClass();
newSubClass("Avnishalok");
  }



}


Output:
Super class Default Constructor
Sub class Default Constructor
Super class parameterized Constructor
Sub class parameterized Constructor


If the statement super("Avnish"); is omitted then the output:
Super class Default Constructor
Sub class Default Constructor
Super class Default Constructor
Sub class parameterized Constructor