Method returns java object

Previous
Next

Method returning primitive variable:

  • Called function can return the value.
  • We collect these values in the calling method
public class Pro
{
    public static void main(String args[])
    {
        int x = Pro.create();
        System.out.println("x main : " + x);
    }
    static int create()
    {
        int x=10;
        return x;
    }
}

Method returning address of object:

public class Pro
{
    public static void main(String args[])
    {
        Pro x = Pro.create();
        System.out.println("x main : " + x);
    }
    static Pro create()
    {
        Pro x = new Pro(); //'x' is local
        return x; // returning address
    }
}

Accessing non static method using static object reference variable:

class Test 
{
	static Test x = new Test();
	static
	{
		int x = 10;
		Test.x.fun();
	}
	public static void main(String[] args) 
	{
		int x = 10;
		Test.x.fun();
	}
	void fun()
	{
		System.out.println("fun...");
	}
}
Previous
Next

Add Comment

Courses Enquiry Form