Sunday, February 25, 2018

Java program : Calling Instance and Static variable/objects

// WE CAN CALL INSTANCE VARIABLES/METHODS USING CLASS NAME, IF WE HAVE A 'STATIC METHOD' WHICH 
// RETURNS A OBJECT OF THE CLASS

// IF WE WRITE SUCH "getOject()" METHOD IN EACH/ANY  CLASS THEN WE WILL BE ABLE/CAN TO ACCESS
//'INSTANCE VARIABLES/METHODS'  BY CLASS_NAME JUST LIKE WE CALL 'STAIC' METHODS USING CLASS_NAME
class InstanceCall
{   
    int a=100;                //INSTANCE VARIABLE
    static int b=200;         //STAIC  VARIABLE
    static InstanceCall getOject()  // THIS 'STATIC' METHOD RETURNS A OBJECT OF THE CLASS
    {
        InstanceCall InstanceCall=new InstanceCall();
        return InstanceCall;
    }
}

class CallInstance
{
    public static void main(String[] args)
    {
        System.out.println(InstanceCall.b);
        System.out.println(InstanceCall.getOject().a);  // WE ACCESS THE "STATIC" getOject() METHOD BY CLASS_NAME,
                                                 // WHICH RETURNS A OBJECT OF THAT CLASS, THEN WE ACCESS
                                                // THE "INSTANCE" VARIABLE 'a', USING THAT OBJECT
    }

}

Thanks
Happy programming!

No comments:

Post a Comment

How can I run a C++ program directly from Windows?

How-can-I-run-a-C-program-directly-from-Windows