Wednesday, 28 August 2019

Class and Object

Class is a logical entity (a class is collection of variables and methods)
Object is a physical entity (is an instance of class)

  Declaration:
       class Car
       {
        variables
        methods
        }

Example:
 public class Car {

         //Class variables
 
    int mod;
    int wheels;
   
    public static void main(String[] args) {
       
        //new Car()---This is the object of the class
        //new keyword is used to create the object
        //a,b,c--Object reference of the variables
        //Car--->class name
        //Car()---->instantiation

       
       
        Car a=new Car();
        Car b= new Car();
        Car c=new Car();
       
        a.mod=2012;
        a.wheel=4;
       
        b.mod=2015;
        b.wheel=3;
       
        c.mod=2019;
        c.wheel=4;
       
        System.out.println(a.mod); //2012
        System.out.println(a.wheel); //4
       
        System.out.println(b.mod); //2015
        System.out.println(b.wheel); //3
       
        System.out.println(c.mod); //2019
   }

Shifting of References

We can shift the object reference from one object to another.When we shift the refrence like:
        a=b;
        b=c;
        c=a;

reference of a becomes b
reference of b becomes c
reference of c becomes b(because now a refer to b)
That is now:
Object b has reference of a and c
Object c has reference of b
Object a has no reference
      
        a.mod=10;
        System.out.println(a.mod);//10
      
        c.mod=20;
        System.out.println(a.mod);//20
        System.out.println(c.mod);//20   


  

No comments:

Post a Comment