Instance Variables and Constructors

 

Python

Java

 

Instance variables are always prefixed with the reserved word self.  They are typically introduced and initialized in a constructor method named __init__.

 

 

 

 

 

 

In the following example, the variables self.name and self.grades are instance variables, whereas the variable NUM_GRADES is a class variable:

 

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)

 

 

 

 

The PVM automatically calls the constructor method when the programmer requests a new instance of the class, as follows:

 

s = Student('Mary')

 

The constructor method always expects at least one argument, self.  When the method is called, the object being instantiated is passed here and thus is bound to self throughout the code.  Other arguments may be given to supply initial values for the objectÕs data.

 

Instance variables are declared at the same level as methods within a class definition.  They are usually given private access to restrict visibility.  They can receive initial values either when they are declared or in a constructor. 

 

Instances variable references may or may not be prefixed with the reserved word this.

 

In the following example, the variables this.name and this.grades are instance variables, whereas the variable NUM_GRADES is a class variable:

 

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];

    }

}

 

The JVM automatically calls the constructor when the programmer requests a new instance of the class, as follows:

 

Student s = new Student("Mary");

 

The constructor may receive one or more arguments to supply initial values for the objectÕs data.

 

Previous

Index

Next