Defining Other Constructors

 

Python

Java

 

A default constructor expects no arguments from the caller, and assigns reasonable defaults to an objectÕs instance variables.  Other constructors expect one or more arguments that allow the programmer to specify these values.

 

Because there is no method overloading, there can be only one __init__ method.  However, multiple methods can be emulated by using optional parameters with default values. 

 

For example, the __init__ method in the following class will set the studentÕs name to an empty string if the caller supplies no name:

 

 

 

class Student:

 

    NUM_GRADES = 5

 

    def __init__(self, name = ''):

        self.name = name

        self.grades = []

        for i in range(Student.NUM_GRADES):

            self.grades.append(0)

 

 

 

 

 

 

 

Usage:

 

s1 = Student('Mary')

S2 = Student()

 

A default constructor expects no arguments from the caller, and assigns reasonable defaults to an objectÕs instance variables.  Other constructors expect one or more arguments that allow the programmer to specify these values.

 

Method overloading allows more than one constructor to be defined, as long as they have different numbers and/or types of arguments.

 

 

In the following example, the Student class is given a default constructor that expects no arguments.  The new constructor calls the other constructor by using the keyword this and the appropriate argument:

 

public class Student{

 

    public static final int NUM_GRADES = 5;

 

    private String name;

    private int[] grades;

 

    public Student(String name){

        this.name = name;

        this.grades = new int[NUM_GRADES];

    }

 

    public Student(){

        this("");

}

 

Usage:

 

Student s1 = new Student("Mary");

Student s2 = new Student();

 

Previous

Index

Next