An object as data member, parameter, return type

Below is an example showing
1. An object can be declared as a data member in a class.
2. An object can be parameter to a method.
3. A method can return an object.

class Test20{

}

class MyXyz{
	private int k;
	private Test20 obj;//object as data member, point 1

	private MyXyz obj1;//an object as data member of itself

	public MyXyz()
	{
		k = 10;
		obj = new Test20();
	}
	public int getK()
	{
		return k;
	}

	public void setK(int p)
	{
		k = p;
	}
}

class Abc{
	private int i,j;

	//object as parameter
	public void display(MyXyz obj)//point 2
	{
		System.out.println("Value:"+obj.getK());
	}

	//returns MyXyz object
	public MyXyz createObj()
	{
		float ftk;
		MyXyz tobj = new MyXyz();
		tobj.setK(34);
		return tobj;//point 3
	}
}

public class ParameterDemo {
	public static void main(String[] args) {

		Abc myobj = new Abc();

		MyXyz obj1 = new MyXyz();
		obj1.setK(201);
		myobj.display(obj1);

		MyXyz obj2 = myobj.createObj();
	}
}

Leave a Reply