Objects: Instances of Classes
Understanding Objects: Instances of Classes
Basics of Objects
- In Java, an object is an instance of a class. The process of creating an object from a class is known as instantiation.
- Objects combine the characteristics and behaviours defined by its class.
- Each object has a unique identity and own set of values for its properties, distinguishing it from other objects, even those of the same class.
Creating Objects
- An object is created using the new operator, followed by the class name and a pair of parentheses.
- Example of object creation:
Robot robby = new Robot();
- Here,
Robot
is the class name,robby
is the object name, andnew Robot()
is the instantiation ofRobot
into an object.
Accessing Object Members
- An object’s fields (variables) and methods can be accessed using the dot operator
.
- To access a field of an object, use
objectName.fieldName;
- To call a method of an object, use
objectName.methodName(parameters);
- Remember that depending upon the visibility modifiers (
private
,protected
,public
), some fields or methods may not be directly accessible.
Constructors
- A constructor is a special method in a class that is automatically called when an object is created from that class.
- Constructors have the same name as the class and have no return type.
- Constructors are used to initialize the object’s state. If no constructor is defined, Java creates a default constructor.
- An example of a constructor for class
Robot
might look like this:public Robot() {...}
Working with Multiple Objects
- It’s possible to create multiple objects from the same class, each with its own set of data.
- For example, you can create multiple
Robot
objects likeRobot robby = new Robot();
andRobot robbie2 = new Robot();
- Each
Robot
has its own separate set of data and is independent of the other.
In Summary
- Understanding objects and how they act as instances of classes is pivotal to mastering Java programming. Objects help in organizing related data and methods, offering a blueprint for creating multiple similar yet distinct entities. The knowledge of creating objects, invoking methods, accessing fields, and implementing constructors is not only fundamental to Java but also forms the basis for object-oriented programming.