How to Create Object in Java

Configurare noua (How To)

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

  1. ClassName object = new ClassName();

Let’s create a program that uses new keyword to create an object.

CreateObjectExample1.java

  1. public class CreateObjectExample1
  2. {
  3. void show()
  4. {
  5. System.out.println(“Welcome to javaTpoint”);
  6. }
  7. public static void main(String[] args)
  8. {
  9. //creating an object using new keyword 
  10. CreateObjectExample1 obj = new CreateObjectExample1();
  11. //invoking method using the object
  12. obj.show();
  13. }
  14. }

Output:

Welcome to javaTpoint

Solutie

Tip solutie

Permanent

Voteaza

(22 din 38 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?