Instantiate Java

In Java, object creation is known as instantiation because an instance of a class is object.

    Let us explain more through Instantiate Java.
 
public class Demo
{
  public static void main(String args[])
  {
    Demo d1 = new Demo();
  }
}

In the above code, d1 is known as object of Demo class. Other way, we can say, d1 object is instantiated. In my own way, I can say, d1 is pointer to the whole class. With d1, we access the constructor and we can call variables and methods. No object like d1, the whole class like Demo is waste.

See the following program on Instantiate Java.
public class Demo
{
  int marks = 75;
  public Demo()                                        //  constructor
  {
    System.out.println("From constructor");
  }
  public void display()                                //  method
  {
    System.out.println("From method");
  }
  public static void main(String args[])
  {
    Demo d1 = new Demo();                              // here, constructor is automatically called
    
    System.out.println("marks variable: " + d1.marks); // calling variable with object
    d1.display();                                      // calling method with object
  }
}


Instantiate Java
Output screenshot on Instantiate Java

In the above code, with object d1, constructor, method and variable are called. Think, without object d1, is it possible to call all these? No, not possible.

More on object creation, the purpose of new keyword, what is Demo() is called, anonymous objects and reference variables are discussed in the following posting of this same Web site.

1. Java Reference Variables – Objects – Anonymous objects

2 thoughts on “Instantiate Java”

  1. Hi Sir,
    class Demo
    {
    int mathMarks = 75; //initialized instance variable
    public void Demo() //constructor
    {
    System.out.println(“From constructor”);
    }
    public void display() //method
    {
    System.out.println(“From method”);
    }
    public static void main(String ar[]) //main method
    {
    Demo d = new Demo(); // here, constructor is automatically called
    System.out.println(“marks in Maths:”+d.mathMarks); // calling variable with object
    d.display(); // calling method with object
    }
    }

    output:
    Process started >>>
    marks in Maths:75
    From method
    <<< Process finished. (Exit code 0)

    In my output constructor is not called. please check my code. i written this program in Notepad++ (http://notepad-plus-plus.org/)

Leave a Comment

Your email address will not be published.