New one in java

Creating Objects

As you know, a class provides the blueprint for objects; you create an object from a class. Each of the following statements taken from the CreateObjectDemo program creates an object and assigns it to a variable:

Point originOne = new Point(23, 94); Rectangle rectOne = new Rectangle(originOne, 100, 200); Rectangle rectTwo = new Rectangle(50, 100);

The first line creates an object of the Point class, and the second and third lines each create an object of the Rectangle class.

Each of these statements has three parts (discussed in detail below):

  1. Declaration: The code set in bold are all variable declarations that associate a variable name with an object type.
  2. Instantiation: The new keyword is a Java operator that creates the object.
  3. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.

Declaring a Variable to Refer to an Object

Previously, you learned that to declare a variable, you write:

This notifies the compiler that you will use name to refer to data whose type is type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable.

You can also declare a reference variable on its own line. For example:

Читайте также:  Data manipulation in python

If you declare originOne like this, its value will be undetermined until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object. For that, you need to use the new operator, as described in the next section. You must assign an object to originOne before you use it in your code. Otherwise, you will get a compiler error.

A variable in this state, which currently references no object, can be illustrated as follows (the variable name, originOne , plus a reference pointing to nothing):

Instantiating a Class

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

Note: The phrase «instantiating a class» means the same thing as «creating an object.» When you create an object, you are creating an «instance» of a class, therefore «instantiating» a class.

The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate.

The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the appropriate type, like:

Point originOne = new Point(23, 94); 

The reference returned by the new operator does not have to be assigned to a variable. It can also be used directly in an expression. For example:

int height = new Rectangle().height;

This statement will be discussed in the next section.

Initializing an Object

Here’s the code for the Point class:

This class contains a single constructor. You can recognize a constructor because its declaration uses the same name as the class and it has no return type. The constructor in the Point class takes two integer arguments, as declared by the code (int a, int b). The following statement provides 23 and 94 as values for those arguments:

Point originOne = new Point(23, 94);

The result of executing this statement can be illustrated in the next figure:

Here’s the code for the Rectangle class, which contains four constructors:

public class Rectangle < public int width = 0; public int height = 0; public Point origin; // four constructors public Rectangle() < origin = new Point(0, 0); >public Rectangle(Point p) < origin = p; >public Rectangle(int w, int h) < origin = new Point(0, 0); width = w; height = h; >public Rectangle(Point p, int w, int h) < origin = p; width = w; height = h; >// a method for moving the rectangle public void move(int x, int y) < origin.x = x; origin.y = y; >// a method for computing the area of the rectangle public int getArea() < return width * height; >>

Each constructor lets you provide initial values for the rectangle’s origin, width, and height, using both primitive and reference types. If a class has multiple constructors, they must have different signatures. The Java compiler differentiates the constructors based on the number and the type of the arguments. When the Java compiler encounters the following code, it knows to call the constructor in the Rectangle class that requires a Point argument followed by two integer arguments:

Rectangle rectOne = new Rectangle(originOne, 100, 200);

This calls one of Rectangle ‘s constructors that initializes origin to originOne . Also, the constructor sets width to 100 and height to 200. Now there are two references to the same Point object—an object can have multiple references to it, as shown in the next figure:

The following line of code calls the Rectangle constructor that requires two integer arguments, which provide the initial values for width and height. If you inspect the code within the constructor, you will see that it creates a new Point object whose x and y values are initialized to 0:

Rectangle rectTwo = new Rectangle(50, 100);

The Rectangle constructor used in the following statement doesn’t take any arguments, so it’s called a no-argument constructor:

Rectangle rect = new Rectangle();

All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent’s no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor ( Object does have one), the compiler will reject the program.

Источник

new operator in Java

When you are declaring a class in java, you are just creating a new data type. A class provides the blueprint for objects. You can create an object from a class. However obtaining objects of a class is a two-step process :

    Declaration : First, you must declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable that can refer to an object. Below is general syntax of declaration with an example :

Syntax : class-name var-name; Example : // declare reference to an object of class Box Box mybox;

A variable in this state, which currently references no object, can be illustrated as follows (the variable name, mybox, plus a reference pointing to nothing):

Instantiation and Initialization : Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator. The new operator instantiates a class by dynamically allocating(i.e, allocation at run time) memory for a new object and returning a reference to that memory. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated. The new operator is also followed by a call to a class constructor, which initializes the new object. 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. In below example we will use the default constructor. Below is general syntax of instantiation and initialization with an example :

Syntax : var-name = new class-name(); Example : // instantiation via new operator and // initialization via default constructor of class Box mybox = new Box();

Before understanding, how new dynamically allocates memory, let us see class Box prototype.

A variable after second step, currently refer to a class object, can be illustrated as follows (the variable name, mybox, plus a reference pointing to Box object):

Hence declaration of a class variable, instantiation of a class and initialization of an object of class can be together illustrated as follows :

Important points :

    The above two statements can be rewritten as one statement.

double height = new Box().height;

Assigning object reference variables

When you assign one object reference variable to another object reference variable, you are not creating a copy of the object, you are only making a copy of the reference. Let us understand this with an example.

Источник

How to Instantiate an Object in Java

Instantiation is a universal concept in Java programming which refers to the process of creating an object of a class. It takes up the object’s initial memory space and returns a reference. The blueprint for the class is provided by an object instantiation. We can create an unlimited number of class objects to represent user-defined data such as lists.

This article will explain the method related to the instantiation of objects in Java.

How to Instantiate an Object in Java?

Instantiation is the process of constructing a class object. That’s why an object is also called the instance of a Java class. In Java, we can make instances of a class by utilizing the “new” keyword.

Syntax

The syntax to instantiate the object of a class:

Let’s see the examples of object instantiation in Java.

Example 1: Instantiate a Single Object in Java

Here, we have a class named “JavaClass” with variables “x”, “y”, a user-defined method “Sum()”, and the predefined “main()” method:

We will create an instance or object of this class named “jc” in the main() method by using a “new” keyword. Using this object, we will access the “Sum()” method and store the returned value in the “ans” int type variable. Lastly, utilize the “System.out.println()” method to print out the sum at the console:

public static void main ( String [ ] args ) {
JavaClass jc = new JavaClass ( ) ;
int ans = jc. Sum ( ) ;
System . out . println ( «Sum of two numbers 5 and 11 is: » + ans ) ;
}
}

Output

Example 2: Instantiate a Single Object in Java Using Multiple Classes

We can also create an object of one class into another class and access the public methods of that class. In this example, we have two classes: “JavaClass1” and “Example”.

JavaClass1” contains a method named “Message()” and a String type variable “name”:

class JavaClass1 {
String name ;
void Message ( )
{
System . out . println ( «JavaClass1 is called.» ) ;
}
}

We will create an object of the class JavaClass1 in the main method of the class Example and access all the public methods of the JavaClass1 in the second class named Example.

Here, we call the method of JavaClass1 in main method of the Example class by using object “jc”:

public class Example {
public static void main ( String [ ] args ) {
JavaClass1 jc = new JavaClass1 ( ) ;
jc. Message ( ) ;
}
}

Output

Example 3: Instantiate Multiple Objects in Java Using Multiple Classes

We can also create multiple objects of the same class. In this example, we have the same two classes as in the above example. Now we will create multiple objects of the class JavaClass1 in the main method of the second class Example.

Javaclass1” contains a constructor, two user-defined methods, and two variables. In the constructor, we will assign the reference variables to the global variables of the class. Whereas, the “Sum()” and the “sub()” methods returns the sum and differences of the “x” and “y” variables:

class JavaClass1 {
int x,y ;
public JavaClass1 ( int a, int b ) {
x = a ;
y = b ;
}
int Sum ( ) {
return x + y ;
}
int sub ( ) {
return x — y ;
}
}

In the main method of the class Example, we will create two objects of the “JavaClass1” as “jc” and “jc1” by passing integer values as arguments. The constructor instantiates the class variables with the given values. Lastly, we will access all the “Sum()” method will “jc” object and “sub()” with “jc1”:

public class Example {
public static void main ( String [ ] args ) {
JavaClass1 jc = new JavaClass1 ( 6 , 9 ) ;
JavaClass1 jc1 = new JavaClass1 ( 19 , 2 ) ;
int ans = jc. Sum ( ) ;
int ans1 = jc1. sub ( ) ;
System . out . println ( «Result: » + ans ) ;
System . out . println ( «Result: » + ans1 ) ;
}
}

Output

We have compiled all of the basic information related to instantiating an object in Java.

Conclusion

In Java, you can instantiate or create an object of the class by utilizing the “new” keyword. The instance of a Java class is another name for an object. You can create an object of the same class or of another class to access their member functions. You can also instantiate multiple objects using multiple classes. In this article, we explained the method to instantiate an object in Java.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

Оцените статью