Problem with Instance
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Cosar_H
Posted On:   Tuesday, January 24, 2006 05:39 AM

Hello, I have a sample class public class sample {} --------------------- and an Instance of sample class in class in1 public class in1 { sample inst1=new sample(); } ---------------------------- How do i use the Instance inst1 of class in1 in class in2? i dont want to create a new Instance. public class in2 { ??? } any idea?    More>>

Hello,
I have a sample class


public class sample

{}



---------------------

and an Instance of sample class in class in1


public class in1

{

sample inst1=new sample();

}


----------------------------
How do i use the Instance inst1 of class in1 in class in2?

i dont want to create a new Instance.

public class in2

{

???

}

any idea?

   <<Less

Re: Problem with Instance

Posted By:   WarnerJan_Veldhuis  
Posted On:   Tuesday, January 24, 2006 06:05 AM

Either via a constructor...


public class Sample {}

public class In1 {
Sample inst1 = new Sample();
In2 inst2 = new In2( inst1);
}

public class In2 {
Sample mySample;
public In2( Sample s) {
this.mySample = s;
}

public void doSomethingWithSample() {
mySample.doSomething();
}
}


... or as parameter of a method:


public class Sample {}

public class In1 {
Sample inst1 = new Sample();
In2 inst2 = new In2();
inst2.doSomethingWithSample( inst1);
}

public class In2 {

public void doSomethingWithSample(Sample s) {
s.doSomething();
}
}


The choice of whether you use a constructor or a method depends on the amount of time that In2 needs to remember the Sample. If the In2 class need to access it often, make Sample a member, and use the cunstructor.
About | Sitemap | Contact