Home : Course Map : Chapter 3 : Java :
Demo 2: Constructors
JavaTech
Course Map
Chapter 3

Introduction
Class Definition
Data Fields
Methods
Constructors
Instantiation
  
Demo 1
  Demo 2
Static Members
  Demo 3

Value&Reference
  Demo 4
Overloading
   Demo 5
Wrappers 
  Demo 6
Autobox/Unbox
   Demo 7
Arrays
  Demo 8
Exceptions
Exercises

    Supplements
MoreAboutObjects
Creating Types

Classes,Objs&JVM

Java OOP vs C++
Garbage Collection
     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

The example below illustrates the two different ways to instantiate a class that contains two constructors. A class can possess any number of constructors and thus allow great flexiblity in the initialization of an instance of that class. (In Chapter 4 we discuss this technique of overloading constructors and methods.)

ConstructorsApplet.java
(Output goes to browser's Java console.)

public class ConstructorsApplet extends java.applet.Applet
{
  public void init () {
    // Create an instance of the Test class using
    // its
no argument constructor.
    Test test = new Test ();
 
    // Here a new Test object is created using
    // its
one argument constructor.
   
 test = new Test (i);
  }

  // Paint message in Applet window.
  public void paint (java.awt.Graphics g) {
 
  g.drawString ("ConstructorsApplet", 10, 20);
  }
}

// This Test class has two constructors.
class Test
{
  Test () {
    System.out.println ("In Test ()");
    System.out.println ("m = " + m);
    System.out.println ();
  }

  // Note that placement of a data field in the class
  // definition is not important

  int m;
  Test (int j) {
    m = j;
    System.out.println ("In Test (int j)");
    System.out.println ("m = " + m);
    System.out.println ();
  }

}

Application version:
ConstructorsApp.java

 

Latest update: Oct. 19, 2004

           Tech
OOP in Tech Apps
Complex Number
Histogram Class
  Demo
More Wrappers

           Physics
OOP in Physics
Particle Class
Root Finding
  Demo 1
Newton Methods
  Demo 2
Exercises

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.