Classes and objects
A class such as Dog is a blueprint, and a blueprint isn't a dog. To get something a program can use, you create an object, also called an instance of the class. In Java you do that with the new keyword.
The new keyword
Here is the line that creates a dog:
Dog rex = new Dog();
It has three parts:
new Dog()builds a freshDogobject in memory. The parentheses call the class's constructor, the code that sets up a new object.Doghas none written out yet, so Java uses a default one that does nothing special.Dog rexdeclares a variable namedrexwhose type isDog.- The
=stores the new object's reference in that variable, sorexnow refers to the dog.
The variable doesn't contain the object itself. It holds a reference to it, a way to find the object. That distinction matters in the next sections.
Many objects from one class
Every evaluation of new Dog() creates a separate object, so one class can produce as many as you need:
Dog rex = new Dog();
Dog buddy = new Dog();
Dog luna = new Dog();
These are three independent Dog objects. They share a blueprint but not their state, so changing one never changes the others. Once the class has fields, each object gets its own copy of them.
References and equality
Because variables hold references, copying a variable copies the reference, not the object. Compare these two cases, using a Dog class that has a public age field:
Dog a = new Dog();
Dog b = new Dog();
Dog c = a;
System.out.println(a == b);
System.out.println(a == c);
This prints:
false
true
Here a and b refer to two different objects, while c refers to the same object as a. For objects, == asks whether two references point to the very same object, not whether the objects look alike. If you write c.age = 5, then a.age is 5 as well, since there is only one object behind both names.
The null reference
A reference variable can also hold null, which means "no object". Declaring Dog rex; as a local variable does not create a dog, and Java refuses to let you read a local variable you haven't assigned. Assigning null is allowed, but calling a method or reading a field through a null reference throws a NullPointerException. Comparing with rex != null is safe, and the lesson's code uses exactly that check.
The lesson's exercise, step by step
The starter code defines an empty Dog class and a mainFunction that prints a line for each of three variables that is not null: rex, buddy and luna. Those variables don't exist yet, so the code doesn't compile. You write the three declarations above the checks:
- Create
rex. Write the type first, then the name, thennew Dog(). - Create
buddy. This is a second call tonew, so it builds a second object that is independent ofrex. - Create
luna. A third call shows that a class can produce any number of objects.
The complete solution:
class Dog {
}
class Solution {
public void mainFunction() {
Dog rex = new Dog();
Dog buddy = new Dog();
Dog luna = new Dog();
if (rex != null) System.out.println("rex exists");
if (buddy != null) System.out.println("buddy exists");
if (luna != null) System.out.println("luna exists");
}
}
Each variable holds a reference to a real object, so none of the three if conditions is false and the program prints three lines:
rex exists
buddy exists
luna exists
The checks can never fail here, because new either returns an object or ends the program with an error. They simply confirm that each variable was declared and assigned.
Common mistakes
- Leaving out
new.Dog rex = Dog();is an error. Withoutnew, Java readsDog()as a method call and can't find a method with that name. - Leaving out the parentheses.
new Dogis incomplete. A constructor call always has parentheses. - Declaring without creating.
Dog rex;only declares the variable. Using it before assigning it is a compile error, and a field of typeDogwould default tonull. - Expecting two names to mean two objects.
Dog b = a;creates no new dog. Onlynewdoes. - Using the wrong type. The type before the variable name and the class after
newnormally match, as inDog rex = new Dog();. The next lessons show when they may differ. - Reusing a name in the same scope. Declaring
Dog rextwice in one method is a compile error. Each of the three objects needs its own variable name.
Key takeaways
- An object is an instance of a class, and
new ClassName()creates one. - A variable of a class type holds a reference to an object, not the object itself.
- Each call to
newproduces a separate, independent object. ==on two object variables checks whether they refer to the same object.- A reference can be
null, and using anullreference to reach a field or method throws aNullPointerException.