Friday, May 27, 2005

Objects

"Programmer: A red-eyed, mumbling mammal capable of conversing with inanimate objects."
(Anonymous)

An object is a class instance (JLS3 2005).

You can create your own objects from your own class like this:

package animalfarm;

class Dog {
}

public class Main {
    public static void main(String[] args) {
        new Dog();
    }
}

The statement that creates the object is new Dog();.

Well, actually, the object may get garbage collected almost before it is created, so we need a pointer for it.

package animalfarm;

class Dog {
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
    }
}

The statement Dog dog = new Dog(); creates the dog pointer and the Dog object. Then the memory location of the object is assigned to the pointer.

The cool thing about OOP is that you can create as many objects as you like from the class! What will happen if you print the objects after they are created?

package bloggingjava;

public class Main {
    public static void main(String[] args) {
        Dog dog1 = new Dog();
        Dog dog2 = new Dog();
        Dog dog3 = new Dog();
        
        System.out.println(dog1 == dog2);
        System.out.println(dog1 == dog3);
        System.out.println(dog2 == dog3);
    }
}
false
false
false

The program compares the references (or pointers) to the objects using the reference equality operator ==. Obviously, each reference points to an unique object, because each comparison is false.

No comments: