This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
RE:Multiple Construtors
Posted by Kishori Sharan on August 08, 2000 at 1:02 PM
Hi You can call another constructor of a class from within a constructor using this( args1, args2 ) ; Here is the example. class Cc { // Construtor 1 Cc ( ) { // your code goes here } Cc ( args1 ){ // your call to construtor must be the first one this() ; // call cc() // Rest of the code goes here } Cc ( args1, args2 ) { this ( args1) ; // call cc ( args1 ) constructor // your code goes here } } //////////////////////// In case of calling the ancestor class constructor use super( arg1, args2... ) instead of this ( args1, args2 ) ; Note the following points in case of construtor calls. 1. Your contructor call using this() or super() must be the first line of code in the constructor. 2. You cannot call two constructors using either super() or this() from a constructor. 3. If you call a constructor on a derived class ( A constructor is called when you create a new object of that class ) then the default construtor for ancestor class is automatically called by java. If you don't have one java compiler will complain. However, if you are calling a constructor of super class from a construtor of derived class then you are free to call one contructor of any kind. //////An example follows to illustrate all construtor rules in action import java.util.* ; import java.io.* ; class Dd { private int roll; private String name ; Dd ( ) { System.out.println ( "No args Constructor... in Dd" ) ; } Dd ( int i ) { System.out.println ( "One arg int constructor..in Dd" ) ; } Dd ( String name ) { this ( ) ; // Calls Dd(); System.out.println ( "One arg String constructor...in Dd" ) ; } Dd ( int i , String name ) { System.out.println ( "Two args constructor...in Dd" ) ; } } class Cc extends Dd { private int roll; private String name ; Cc ( ) { System.out.println ( "No args Constructor.. in cc." ) ; } Cc ( int i ) { // cannot call two ancetor/own constructors this() ; //OK /****** super ( i ) ; // Error you already called this() ****/ System.out.println ( "One arg int constructor .. in cc" ) ; } Cc ( String name ) { // By default calls Dd() ... Try commenting Dd ( ) System.out.println ( "One arg String constructor .. in cc" ) ; } Cc ( int i , String name ) { super ( i, name ) ; // Calls Dd ( int i, String name ) System.out.println ( "Two args constructor.. in cc" ) ; } public static void main ( String[] main ) { Cc aa = new Cc ( "Chanda" ); } } Thanx Kishori
Replies:
|