-1

Here in this code snippet of Object Relation, I am taking reference of Class Two in Class One, and through it I am accessing class Two's members.

What if I create Class Two's Object in Class One itself and then access its methods? What will be the difference in doing it ?

I know I am missing some concept here but I am not getting it.

// Object Relation Using References

 package Object_Relation;
 class One {
    // Instance Variables
    int x;
    Two t;
    public One(Two t) {
        this.t = t;
        x=10;
    }

    void display() {
        System.out.println("Class One Members : ");
        System.out.println("x = "+x);
        System.out.println("Displaying Class Two Members using its Method");
        t.display();
   System.out.println("Displaying Class Two Members using its reference :");
        System.out.println("y = "+t.y);
    }
}

class Two {

    //  Instance Variables
    int y;
    public Two(int y) {
        this.y = y;
    }

    public void display() {
        System.out.println("y = "+y);
    }

}

public class UsingReference {
    public static void main(String[] args) {
        Two t2 = new Two(20);
        One o = new One(t2);
        o.display();
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Jian25
  • 11
  • 1
  • 5
  • Is this a real question? What are you asking? – Tim Biegeleisen Aug 08 '16 at 16:17
  • See if the following helps: http://stackoverflow.com/questions/2399544/difference-between-inheritance-and-composition – PM 77-1 Aug 08 '16 at 16:21
  • @TimBiegeleisen My Query is that i am able get the same output from both the ways, I am confused in both the approaches. – Jian25 Aug 08 '16 at 16:34
  • The difference is that you have two pointers to follow instead of just one. The memory location of One and Two have no relationship and could be anywhere. – Johnny V Aug 08 '16 at 17:59

1 Answers1

0

I am not sure what exactly the question is?

But here in the example One and Two both are different classes. And in-order to access the non-static member variables you need a object of class Two.

Are you looking for some concept about inner class in java:- Example

public class OuterClass {

  int i;

  public void method1() {
    System.out.println("Inside Method 1");
  }

  class InnerClass {
    int j;

    public void method2() {
      System.out.println("Inside Method 2");
    }
  }

  public static void main(String[] args) {
    // To instantiate an inner class, you must first instantiate the outer class
    OuterClass outerObject = new OuterClass();
    outerObject.method1();

    // Then, create the inner object within the outer object
    OuterClass.InnerClass innerObject = outerObject.new InnerClass();
    innerObject.method2();
  }

}

PS: Here InnerClass is a member of OuterClass.

Dyuti
  • 184
  • 4