Thursday, February 12, 2015

Classes and Objects in Java

Class

  • Class is the collection of similar type of objects which have some common properties.
  • Class is a concept which is implemented by object.
  • Class is a blueprint of java program from which we create object, then object is instance of class.
  • We can also say that class is a collection of variables and methods.

Class
{
         Methods: Represent Property
Variables: Represent Behavior
}

Object

  • Any real world entity which have physical existence either living or non living is called an object.
  • It is a runtime memory area. Object goes to heap.
Classes and Objects in Java

How to Create an Object?

  • In Java object of any class is created using new keyword.
  • new keyword reserve the memory for an object in heap and generate an implicit reference id which is stored in a reference variable.

class Emp
{
                String name;
                int salary;

                void get(String n1,int s1)
                {
                                name=n1;
                                salary=s1;
                }

                void show()
                {
                                System.out.println(name);
                                System.out.println(salary);
                }

                public static void main(String...s)
                {
                                Emp e1=new Emp();
                                e1.get("aa",101);
                                e1.show();
                                new Emp().get("bb",102);            //Anonymous Object
                                new Emp().show();                         //Anonymous Object

                }
}

Note: Reference variables and local variables goes to stack and methods goes to method area



Output

Classes and Objects in Java Program

  • In above example total three objects are created. Firstly an object is created using new operator and its reference id is stored in reference variable e1. Then using e1 we call get() and show() methods. After that we are creating two anonymous objects. You can see that we are getting different outputs in three objects.
  • Anonymous object is an object without name.
  • We can store one reference id into more than one reference variable.
    Example: Emp e1=new Emp();
                   Emp e2=e1;


If you find anything wrong or missing in above tutorial then please mention it in comment section.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.