Objects

Think of Java classes as a more complicated variable type. For example, we wrote a Dog class, so now we will be able to create variables of type Dog. These variables are similar to ordinary variables, but they each have their own methods and fields. These types of variables are called objects, whereas ints and doubles are primitive types.

Syntax and examples

Declaring an object variable has the sam format as declaring a primitive type variable:

type name;

Recall our Dog class from the previous section:

public class Dog 
{
    //fields
    private String name;
    public String breed;

    //constructor
    public Dog() 
    {
        name = "Fido";
        breed = "Mutt";
    }
}

We can declare a variable of type Dog like this:

Dog d1;

Initializing an object variable works a little differently than initializing a primitive type variable. We must call the object’s constructor to set of values for its fields. Here is the format of initializing (also called instantiating) an object:

name = new ClassName(params);

Here, name is the name of the object variable, ClassName is the name of the class whose tytpe we are using, and params are the parameters passed to the constructor. Here’s how we would create a new Dog object:

d1 = new Dog();

This calls the no-parameter Dog constructor, and initializes the Dog’s name to “Fido” and its breed to “Mutt”. Supppose instead the Dog class had this version of the constructor (with parameters for the name and breed):

public Dog(String n, String b) 
{
    name = n;
    breed = b;
}

Here’s how we could create a Dog object now:

Dog d2 = new Dog("Rover", "Labrador");

Keep in mind that although the d1 and d2 variables are both of type Dog, and both have values for the name and breed, they are completely separate in memory. Dog is just a template that allows us to create variables.

Accessing fields

Once we have created an object, we can access any of its public members. In the Dog class, the breed variable is public, so we can access it. Here’s the format for accessing public fields:

objectName.variableName

For example, here’s how we would print the breed of both dogs:

System.out.println(d1.breed);
System.out.println(d2.breed);

This would print:

Mutt
Labrador