简体   繁体   中英

passing object of class to another class

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!

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM