Sunday, 29 January 2017

OBJECT AND CLASS IN JAVA

Class is a group of objects which have common properties. Suppose we want to design a Car then we need to design its blueprint or template and then it we will define all our business logics. So the structure or blueprint is known as class. As java is object-oriented programming language so everything we do has to be designed inside class. A class in java can contain –
  • ·        Fields
  • ·        Methods
  • ·        Constructors
  • ·        Blocks
  • ·        Nested class and Interface.



Object is an instance of a class. The memory space which is allocated for the members of a class, dynamically at the runtime, can be called as an object. Objects could be created only for the classes, thus objects can’t be created without a class. Example Car, Chair, Bike etc. Suppose Bank is n object created as an Interface in java and HDFCBank, ICICIBank as classes with bank operations like withdraw, deposit implementations.

Creating an object

Let us take an example –
class Trial2 {
          int i=5;
          public void display()
          {
                   System.out.println("Hello java");
          }
}
class Trial{
          public static void main(String[] args) {
                   Trial2 obj = new Trial2();
                   System.out.println(obj.i);
                   Obj.show();                  
          }
}

In the above example we have created an object in the Trial class as –
Trial2 obj = new Trial2();
As we know that java is based on the concept of OOPS so everything will be in terms of class. If we want to create object then we have to use class name. In the above example we have created an object for class Trial2. Here obj is not an object it is a reference variable. To create object we use new keyword with constructor name which is same as class name to initialize memory for an object. The memory for the object is created inside Heap memory, but the memory for the variables are created inside Stack memory. Whenever we created object then the reference variable i.e. obj is stored inside the Stack memory with the memory address of a particular object. And that reference variable points to a particular address inside the Heap Memory.

Suppose again if we created another object with same reference name then the previous object is moved for garbage collection and the reference variable would now point to the new memory address.

No comments:

Post a Comment