Object Reference variable in java

Previous
Next

Object Reference Variable:

  • “new” keyword allocate object memory at random location.
  • Non static variable get memory inside object(if any).
  • Constructor initialize(assign values to non static variables) object after creation.
  • After object initialization, constructor returns the address of object.
  • We need to collect the address into a variable called “Object Reference Variable”
  • The variable should be of “Class type”.
public class Pro
{
    Pro()
    {
        System.out.println("Address in constructor : " + this);
    }
    public static void main(String args[])
    {
        Pro obj = new Pro();
        // System.out.println("Address in main : " + this);   Error:
        System.out.println("Address in main : " + obj);
    }
}

Access Static and Non static methods from main():

class Pro 
{
	Pro(){
		System.out.println("Object is ready");
	}
	public static void main(String[] args) 
	{
		Pro p = new Pro();
		Pro.m1();
		p.m2();
	}
	static void m1(){
		System.out.println("Static method");
	}
	void m2(){
		System.out.println("Non static method");
	}
}
  • We use ‘this’ keyword in Constructor(non static area) to access the object.
  • We use “Object reference variable inside the main(static area) to access the object.
public class Pro
{
    Pro()
    {
        System.out.println("Constructor");
        Pro.m1();
        this.m2();
    }
    public static void main(String args[])
    {
        Pro obj = new Pro();
        System.out.println("Main");
        Pro.m1();
        obj.m2();
    }
    static void m1()
    {
        System.out.println("Static m1");
    }
    void m2()
    {
        System.out.println("Non static m2");
    }
}

Previous
Next

Add Comment

Courses Enquiry Form