Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pass objects between classes

Tags:

c#

object

So what I'm trying to do here is pass the same copy of a class (class A) to another class (class B), but class B is instanced in class A.

Using a new statement in class B won't work because it would cause an infinite loop, as well as creating a new instance of it, when I want to be able to use variables from the 1st instance of class A.

I know about object.equals() but I can't use it until I define the class A's object in class B. Just using object.equals results in a null reference.

public partial class class_A : Form
{
    public class_B _class_B = new class_B;
    public Int32 var; 

    private void setclassA()
    {
        _class_B._class_A.equals(this);
    }
}

public class class_B
{
    public class_A _class_A;        // I know this is null
    // code
}

Like I said I want to avoid instancing a new copy of class A because I want the values in class A to be set.

I've tried using a method to do it but still get a null reference.

like image 254
Shaken_U Avatar asked May 06 '15 02:05

Shaken_U


People also ask

How do you pass objects between classes 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.

How do you pass an object to another class 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.

How do you pass a class as an object?

To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables. Syntax: function_name(object_name); Example: In this Example there is a class which has an integer variable 'a' and a function 'add' which takes an object as argument.

Can we pass object as parameter in Java?

In Java, we can pass a reference to an object (also called a "handle")as a parameter. We can then change something inside the object; we just can't change what object the handle refers to.


1 Answers

Pass A in the constructor of B:

public class A
{
   private B _b;

   public A()
   {
       _b = new B(this);
   }
}

public class B
{
    private A _a;

    public B(A a)
    {
        _a = a;
    }
}

As mentioned in the comments you're completely misunderstanding .Equals(). It's used to compare whether two objects are equal not clone / pass references.

like image 83
RagtimeWilly Avatar answered Oct 29 '22 16:10

RagtimeWilly