9

I have two classes. Class A and Class B.

I have a function in Class A that i would like to use in class B. I was thinking about passing a reference of Class A to the constructor of Class B and then call the function after that.

Would that work? Can someone show me an example?

Thanks in advance!

AlexPad
  • 10,364
  • 3
  • 38
  • 48
prolink007
  • 33,872
  • 24
  • 117
  • 185
  • Well you can't pass by reference in java. A good read here http://www.yoda.arachsys.com/java/passing.html . – CoolBeans Jan 17 '11 at 21:18
  • 4
    @CoolBeans. You can't pass by reference, but you can pass a reference. And that's in fact what happens naturally when you think you're passing an object. – Don Roby Jan 17 '11 at 21:31

2 Answers2

23

Yes, it will work. And it's a decent way to do it. You just pass an instance of class A:

public class Foo {
   public void doFoo() {..} // that's the method you want to use
}

public class Bar {
   private Foo foo;
   public Bar(Foo foo) {
      this.foo = foo;
   }

   public void doSomething() {
      foo.doFoo(); // here you are using it.
   }
}

And then you can have:

Foo foo = new Foo();
Bar bar = new Bar(foo);
bar.doSomething();
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
3

Do something like this

class ClassA {
    public ClassA() {    // Constructor
    ClassB b = new ClassB(this); 
}

class ClassB {
    public ClassB(ClassA a) {...}
}

The this keyword essentially refers to the object(class) it's in.

ahodder
  • 11,353
  • 14
  • 71
  • 114