pro*_*007 8 java reference class
我有两节课.Class A和Class B.
我有一个功能Class A,我想使用class B.我正在考虑将引用传递Class A给构造函数,Class B然后调用该函数.
那会有用吗?有人能告诉我一个例子吗?
提前致谢!
Boz*_*zho 21
是的,它会起作用.这是一个很好的方式.你只需传递一个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.
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以:
Foo foo = new Foo();
Bar bar = new Bar(foo);
bar.doSomething();
Run Code Online (Sandbox Code Playgroud)