Keyword Used in Instantiating a Class in Java



An object is created from a class. In Java, the new keyword is used to create new objects.

There are three steps when creating an object from a class −

  • Declaration − A variable declaration with a variable name with an object type.

  • Instantiation − The 'new' keyword is used to create the object.

  • Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

Following is an example of creating an object −

Example

Live Demo

public class Puppy {
   public Puppy(String name) {
      // This constructor has one parameter, name.
      System.out.println("Passed Name is :" + name );
   }
   
   public static void main(String []args) {
      // Following statement would create an object myPuppy
      Puppy myPuppy = new Puppy( "tommy" );
   }
}

Output

Passed Name is :tommy
Updated on: 2019-07-30T22:30:20+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements