Situatie
The object is a basic building block of an OOPS language. In Java, we cannot execute any program without creating an object. There is various way to create an obiect in java that we will discuss in this section, and also learn how to create an object in Java.
java provides five ways to create an object.
- Using new Keyword
- Using clone() method
- Using newInstance() method of the Class class
- Using newInstance() method of the Constructor class
- Using Deserialization
Using new Keyword
Using the new keyword is the most popular way to create an object or instance of the class. When we create an instance of the class by using the new keyword, it allocates memory (heap) for the newly created object and also returns the reference of that object to that memory. The new keyword is also used to create an array. The syntax for creating an object is:
- Using new Keyword
- Using clone() method
- Using newInstance() method of the Class class
- Using newInstance() method of the Constructor class
- Using Deserialization
Backup
- ClassName object = new ClassName();
Let’s create a program that uses new keyword to create an object.
CreateObjectExample1.java
- public class CreateObjectExample1
- {
- void show()
- {
- System.out.println(“Welcome to javaTpoint”);
- }
- public static void main(String[] args)
- {
- //creating an object using new keyword
- CreateObjectExample1 obj = new CreateObjectExample1();
- //invoking method using the object
- obj.show();
- }
- }
Output:
Welcome to javaTpoint
Leave A Comment?