Thursday, April 18, 2013

Passing an object as parameter to a method

Passing an object as parameter is always a confusing concept. here is a java code given below which might help you understand this concept .

/*========================================*/

public class HelloWorld{
     public static void main(String []args){
       myroom obj = new myroom();
       dadsroom obj1 = new dadsroom();
       obj1.love(obj);
     }
}
 class myroom{
public int x;
    public int y =3;
}
class dadsroom{
 void love(myroom o){
       System.out.println(o.x +"and"+ o.y);
   }
}
/*========================================*/

SHOULD I CALL IT EXPLANATION ? :
 I've created three class in above code, one is HelloWorld which combines the main method, next is myroom, and last one is dadsroom. In main method, I've created an object of myroom "obj" and another object of dadsroom "obj1". dadsroom is having a method love which is receiving object of myroom and then printing instance variable using object of myroom. In main, I've called love method using object of class dadsroom and passing object of myroom  as parameter..

Let's have a formal EXPLANATION:
what i am trying to do is, i am having a template of myroom and also a template of dadsroom through their objects, now I am adding a room which is same as myroom(every thing is same as myroom cause it is instance of myroom) into dadsroom, now a room which is same as myroom is attached with dadsroom, I can access every feature (which was having myroom) through dadsroom. An object of myroom is attached with dadsroom by passing object of myroom.

No comments:

Post a Comment