An object is a defined model (or an implementation) of a Class. Every object is created from a class with some common properties (Attributes) . However, certain properties can be unique to a object, and these are known as instance attributes.
An object needs to be instantiated to be stored in a program. As such, an instantiated object is known as an instance.
Instantiation
To actually store an object in memory, we need to instantiate it. Generally, this is done by declaring it and then using memory allocation to store it.
Java
//Assume Circle is a class, and Circle(x) creates a circle of x radius
Circle smallCircle = new Circle(30);
This line does multiple steps at once:
- Creates a Pointer of type
Circle
- Assigns that pointer to a new block of memory which Circle will take up.
new
is Java’s keyword to let the JVM (Java Virtual Machine) allocate memory
Alternatively, we can do:
Circle smallCircle; //smallCircle points is a null pointer
smallCircle = new Circle(30); //Now assigned
Accessing Methods and Attributes
In Java, the dot (.) operator is used to access an object’s methods and attributes:
System.out.println(smallCircle.radius) //.radius returns the attribute 'radius'
smallCircle.resize() //.resize() invokes the resize() method
: Be very very careful to make sure an object is first instantiated before trying to access any methods or instance variables.