What Are Object And How To Create Object In Java ?

Definition :

- Objects are the basic run time entity or in other words object is a instance of a class. All these objects have a state and behavior.If we consider the real-world we can find many objects around us, Cars, Dogs, Humans etc. If we consider a dog then its state is name, breed, color, and the behavior is barking, wagging, running.Software objects also have a state and behavior.

Creating an Object :

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 o a constructor. This call initializes the new object.

Syntax for creating Object :

class_name object_name = new class_name();

Example :

class demo
{
int i=10;
void display()
{
System.out.println("www.java-answers.blogspot.com");
}
public static void main(String args[])
{
demo x = new demo();
x.display();
System.out.println("value of i = " +i);
}
}

Output :
www.java-answers.blogspot.com
value of i = 10

Accessing Methods Using Object :

Instance variables and methods are accessed via created objects.you can learn about Methods and how to create Methods from what are methods in java tutorial. To access a Method from the above example should be as follows:

/* First create an object */
demo x = new demo();

/* Now you can call a class method as follows */
x.display();

The above example program creates a object with name x using 'new' keyword and after creating the object we can access the method and variable of class using this objects as shown in the above program.This is how objects are created in java.

1 comment:

Unknown said...

Thank you for the answer .

Post a Comment