Creating An Object Of A Class

A class is of no use until its object is created .An object is the instance of class and it will create memory for the class member.Without objects class variables and method are not given any memory location.

Creating object of a class is a two step process.First we must declare a variable of the class type.This variable does not define an object,it is simply a variable that can refer to an object.At second step we must acquire an actual copy of the object and assign it to that variable. We can do this by using new operator,it dynamically allocates memory for an object.Object of the class is alwyas created in the main class.

Syntax:-

 

class user_defined_class_name

{

        Member variables;

        Member methods();

}

 

Class main_class_name

{

    public static void main(String args[])

   {

         user_defined_class_name obj=new user_defined_class_name();

         // This statement combines the two steps.This can be understand by writting the above  statement as below:-

    user_defined_class_name obj;  //declare reference to object

   obj=new user_defined_class_name();    //allocate a user_defined_class_name object

 

Example:-The concept of classes can be understood by following example:-

 

 

import java.io.*;

class test1    //user defined class name

{

     void getdata()  //user defined method name

  {

                     String name;    

                        int roll;           //member variable

try

{

DataInputStream dis=new DataInputStream(System.in);

       System.out.println(“Enter the name:”);

       name=dis.readLine();

System.out.println(“Enter tthe roll no.:”);

roll=Integer.parseInt(dis.readLine());

}

catch(Exception e)

{}

     }

}

 

class test     //main class in which the object of the class has to be created

{

public static void main(String args[])

{

int age;

try

{

DataInputStream dis=new DataInputStream(System.in);

test1 obj=new test1();    //creating the object of the class test1

obj.getdata();    //member method calling with the help of object

System.out.println(“Enter the age of the student:”);

age=Integer.parseInt(dis.readLine());

}

catch(Exception e)  {}

}

}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s