Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing object of class to another class

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 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?

Thanks in advance!

like image 232
prolink007 Avatar asked Jan 17 '11 21:01

prolink007


People also ask

How do you pass a class object to another class?

To do this, either we can use Object. clone() method or define a constructor that takes an object of its class as a parameter.

How do you pass a class object to another class in Python?

Passing object as parameter In class Person, MyClass is also used so that is imported. In method display() object of MyClass is created. Then the my_method() method of class MyClass is called and object of Person class is passed as parameter. On executing this Python program you get output as following.

Can we assign object of one class in another class?

Through class conversion, one can assign data that belongs to a particular class type to an object that belongs to another class type.

How do you pass an object to another object in Java?

We have a method coypObject() which accepts an object of the current class and initializes the instance variables with the variables of this object and returns it. In the main method we are instantiating the Student class and making a copy by passing it as an argument to the coypObject() method.


2 Answers

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();
like image 143
Bozho Avatar answered Sep 28 '22 08:09

Bozho


Do something like this

class ClassA {
    public ClassA() {    // Constructor
    ClassB b = new ClassB(this); 
}

class ClassB {
    public ClassB(ClassA a) {...}
}

The this keyword essentially refers to the object(class) it's in.

like image 37
ahodder Avatar answered Sep 28 '22 08:09

ahodder