next up previous contents
Next: Class: Methods Implementation Up: Java Notes Previous: Classes: Constructors

Classes: Constructors 1: Example

/**
 *  This code is from the book:
 *  Winder, R and Roberts, G (1998)
 *  Developing Java Software
 *  John Wiley & Sons.
 *  It is copyright (c) 1997 Russel Winder
 *  and Graham Roberts.
 */

import java.util.Vector;

class l1ClCons1{//Constructor1
  //instance variables that get default initialization
  //unless assigned to in a constructor
  private int initialSize;
  private Vector v;

  //Default constructor
  public l1ClCons1(){
    //This assignment is actually not needed;
    //done by default initialisation
    initialSize = 0;
    v = new Vector();
  }

  //Create vector of a given size
  public l1ClCons1(int size){
    initialSize  = size;
    v = new Vector(size);
  }

  //Create vector of given size and initialize all
  //the elements to the string argument
  public l1ClCons1(int size, String val){
    initialSize  = size;
    v = new Vector(size);
    for (int i = 0; i < size; i++){
      v.addElement(val);
    }
  }

  public static void main(String[] args){
    //Create object with default constructor
    l1ClCons1 c1 = new l1ClCons1();
    //Other constructors
    l1ClCons1 c2 = new l1ClCons1(10);
    l1ClCons1 c3 = new l1ClCons1(10,"Hello");
  }
}
/******** sample compilation & run ********
# javac l1ClCons1.java 
# java l1ClCons1
# 
******************************************/



Ananda Amatya
9/15/1999