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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With