Wednesday 4 December 2013

Java object example, How to create object in java.




In this example, we will see how to create a object in java. An object is a main feature of object oriented programming concept. It is an instance variable of class or real-world entity. We can declare a object by using new operator. The new operator dynamically allocate memory of object and returns a reference for object.

Here, a ObjectExample class is a supper class of ObjectDemo class. Subclass has main method, and also supper class has a show() method. Which is use for displaying a string "Hello world.". The obDemo is a object of supper class.

Syntax

ClassName object=new ClassName();
ClassName object (Reference of object)
ClassName object=new ClassName(); (allocation)

Code:
ObjectDemo.java

package com.devmanuals;

class ObjectExample {
        public void show() {
                System.out.println("Hello world.");
        }
}
public class ObjectDemo {
        public static void main(String[] arg) {
                ObjectExample obDemo = new ObjectExample();
                obDemo.show();
        }
}
Output:
Hello world.

No comments:

Post a Comment