Friday, April 10, 2009

Instance Variables

Each Object instance, i.e. every person (tom, dick, harry) you create from the Person class specification, can have its own instance variables.

Variables are things that can change. Ones that are stored and encapsulated within an Object are called instance variables, because there's one variable per instance.

We can change our Person Class to look like this:


public class Person
{
    private String name;
    private String birthPlace;
    
    public Person(String name, String birthPlace)
    {
        this.name = name;
        this.birthPlace = birthPlace;
    }
}



You can see it's quite different to what we previously had.

Firstly, you can see two new instance variables we've added - 'name' and 'birthPlace'. Both are of type 'String' which is an inbuilt Object which holds letters and characters.

We defined them within the Class by using the private package modifier, meaning only methods within this class can have access to them. No other Object can touch them directly, if they were public, they could.

You'll see we changed the 'signature' of the constructor to also take these two new variables.

What this means is that when we create a Person Object we can pass two Strings in and these can get assigned to the private instance variables.

We do this by using the keyword 'this': this.name = name means that the value of name which has been passed into the constructor (the right hand side 'name') is being assigned to the Object's instance variable (the left hand side 'this.name').

i.e. we could create a dean Person instance by doing this:


Person dean = new Person("Dean", "Crawley");


The Object instance 'dean' now has it's instance variables assigned the values Dean and Crawley (respectively!).

No comments: