本文介绍了将类的引用传递给另一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个类。 A类
和 B类
。
函数在 A类
,我想在类B
中使用。我正在考虑将 A类
的引用传递给 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?
提前感谢!
推荐答案
是的,它会工作。这是一个体面的方式。您只需传递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();
这篇关于将类的引用传递给另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!