1.12 - Objects: Instances of Classes
An object is a specific instance of a class with its own set of attribute values. A class is the blueprint, it’s the formal description of what attributes and behaviors an object of that type will have.
Think of a class as a cookie cutter and objects as the cookies. One class can make lots of objects, and each object has its own values for the attributes. For example, if a
Student class has the attributes name and gradeLevel, one Student object might store "Maya" and 11 while another stores "Leo" and 9. Same class, same attributes, different values.You can build a class hierarchy by putting shared attributes and behaviors into one class, called a superclass. Classes that extend that superclass are called subclasses, and they inherit the superclass’s attributes and behaviors without needing to rewrite them. This relationship is called inheritance.
For example, a
Vehicle superclass could hold what all vehicles share, like a number of wheels and a way to move. Car and Bicycle would be subclasses: each one gets those from Vehicle automatically and can add its own attributes and behaviors on top.Note: actually designing and implementing your own inheritance relationships is outside the scope of this course, you just need to understand the concept.
Every class in Java, without exception, is a subclass of the
Object class.That’s why every object, no matter its class, has the methods from
Object, like toString and equals (both are on the Java Quick Reference). You’ll see toString in action in 1.15.A variable of a reference type holds an object reference, basically the memory address where that object lives.
String greeting; // reference type variable, no object yet
This is the big difference from primitives. A primitive variable stores its value directly, but a reference variable stores where the object is, not the object itself:
int count = 5; // count holds the value 5 itself String name = "Dove"; // name holds a reference to a String object String other = name; // copies the reference, so both refer to the same object
In diagrams, a reference is usually drawn as an arrow from the variable to the object.