CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Classes

Objects and Classes
Object
Constructors

Constructors are a special kind of methods that are invoked to construct objects.

How to code constructors

  • The constructor must use the same name and capitalization as the name of the class.
  • If you don't code a constructor, Java will create a default constructor that initializes all numeric types to zero, all boolean types to false, and all objects to null.
  • To code a constructor that has parameters, code a data type and name for each parameter within the parentheses that follow the class name.
  • The name of the class combined with the parameter list forms the signature of the constructor.
  • Although you can code more than one constructor per class, each constructor must have a unique signature.
  • The this keyword can be used to refer to an instance variable of the current object.

The syntax for coding constructors

public ClassName([parameterList])
{
    // the statements of the constructor
}

A constructor that assigns default values

public Product()
{
   code = "";
   description = "";
   price = 0.0;
}

A custom constructor with three parameters

public Product(String code, String description,
double price)
{
    this.code = code;
    this.description = description;
    this.price = price;
}

Another way to code the constructor shown above

public Product(String c, String d, double p)
{
    code = c;
    description = d;
    price = p;
}

A constructor with one parameter

public Product(String code)
{
    this.code = code;
    Product p = ProductDB.getProduct(code);
    description = p.getDescription();
    price = p.getPrice();
}
Previous | Product class | Instance variables | Constructors | Methods | Overload methods | this | Next