将类的对象传递给另一个类 [英] passing object of class to another class

查看:74
本文介绍了将类的对象传递给另一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两节课. Class AClass B.

我要在class B中使用的功能在Class A中.我正在考虑将Class A的引用传递给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?

提前谢谢!

推荐答案

是的,它将起作用.这是一种不错的方法.您只需通过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();

这篇关于将类的对象传递给另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆