且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将类的对象传递给另一个类

更新时间:2023-01-08 14:32:37

是的,它将起作用.这是一种不错的方法.您只需通过A类的实例:

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.
   }
}

然后您可以拥有:

Foo foo = new Foo();
Bar bar = new Bar(foo);
bar.doSomething();