An object consists of:
Class -- a blueprint for objects. A class is a user-defined type that describes and defines objects of the same type. A class contains a collection of data and method definitions.
An object is a single instance of a class. You can create many objects from the same class type.
ClassName objectReference; objectReference = new ClassName(); (or combined into one statement) ClassName objectReference = new ClassName();Examples:
Circle myCircle; // where Circle is a class myCircle = new Circle(); Dog fido = new Dog(); // where Dog is a classCaution: Since the name used to refer to an object is a reference variable, and not the object itself, it is important to note that any assignments done on such a variable are just on the reference. For example, if we create two objects, and then assign their variables together:
Circle c1 = new Circle(); Circle c2 = new Circle(); c1 = c2;... the last statement (c1 = c2) does not copy circle c2 into c1. Instead, it copies the reference varaible c2 to c1, which means that both reference variables are now referring to the same object (the second one, c2).
objectReference.data objectReference.method(arguments) // a call to a methodExample:
Circle c1 = new Circle(); c1.radius = 10; // access radius instance variable // compute and print the area with the findArea method System.out.print("Area = " + c1.findArea());
The public members of a class make up the interface for an object (i.e. what the outside builder of the object can use). The user of an object is some other portion of code (other classes, functions, main program).
Although there is no set rule on what is made public and what is made private, the standard practice is to protect the data of a class by making it private. Provide access to the data through public methods, which can maintain control over the state of the object.
Reasons for data hiding:
A constructor is easy to recognize because:
A constructor is automatically invoked when an object is created with new.
c1 = new Circle(); // invokes default constructor c2 = new Circle(9.0) // invokes a constructor with one parameterThe usual purpose of a constructor is to perform any initializations on the object when it is created (i.e. primarily the instance variables)