If you cannot find what you are looking for. Please visit our sitemap

Java Classes Declaring Objects

                        Java Classes Declaring Objects

When you create a class, you are creating a new data type You can use this type to declare objects of that type. Obtaining objects of a class is a two step process. First, we declare a variable of the class type. This variable does not define an object. It is simply a variable that can refer to an object. Then we acquire an actual, physical copy of the object and assign it to that variable. we do this by using new operator. The new operator dynamically allocates memory for an object and returns a reference to it. This reference is, more or less, the address in memory of the object allocated by new. This reference is then stored in the variable. In java, all class objects must be dynamically allocated.

rectangle myrectangle;               // declares reference to object
myrectangle = new rectangle();  // allocate a rectangle object

New Operator:

The new operator dynamically allocates memory for an object. It has general form:

 class-var = new classname();

class-var is a variable of the class type being created. Class name is the name of the class that is being instantiated. Class name followed by parentheses specifies the constructor for the class. A constructor defines what occurs when an object of a class is created. Constructors are an important part of all classes and have many significant attributes.Most real-world classes explicitly define their own constructors within their class definition. If no explicit constructor is specified, then java will automatically supply a default constructor.

Assigning Object Reference Variables:

Object reference variables act differently than you might expect when an assignment takes place. For example, what do you think the following fragment does?

rectangle r1 = new rectangle();
rectangle r2  = r1;

After this code executes, r1 and r2 will both refer to same object. The assignment of r1 to r2 did not allocate any memory or copy any part of the original object. It simply makes r2 refer to the same object as does r1. Thus, any changes made to the object through r2 will affect the object to which r1 is referring, since they are the same objects.

Written by: Asad Hussain