Site hosted by Angelfire.com: Build your free website today!
 

Class Constructor

Dog.java

class Dog {
    static int legs = 4;
    static int dogCount = 0;
    int dogID;
    String name;
    String owner;
    String color;
    public Dog(String name, String owner, String color) {
        dogID = dogCount++;
        this.name = name;
        this.owner = owner;
        this.color = color;
    }
    public static int howManyLegs() {  //a class method
        return legs;
    }
    public String whatColor() {  //an instance method
        return color;
    }
    public void printInfo() {
        System.out.println(owner + "'s dog " +
            name + "(ID=" + dogID + ") is " + color + 
            " and has " + legs + " legs.");
    }
}

A constructor is a special method that returns an object of the class that it is defined. In Java, a constructor is named the same as the class.