passing object of class to another class

后端 未结 2 1481
礼貌的吻别
礼貌的吻别 2020-12-05 05:55

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

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 06:20

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

提交回复
热议问题