In class B
, how can I create an object of class A
other than the process of object creation (i.e. without creating an object having null
)?
class A
{
public int one;
A(A a)
{
a.one=1;
}
}
class B
{
public static void main(String...args)
{
//now how to create an object of class A over here.
}
}
If we know the name of the class & if it has a public default constructor we can create an object Class. forName. We can use it to create the Object of a Class.
In Java, we can create Objects in various ways: Using a new keyword. Using the newInstance () method of the Class class. Using the newInstance() method of the Constructor class. Using Object Serialization and Deserialization.
Using new Keyword The new keyword is also used to create an array. The syntax for creating an object is: ClassName object = new ClassName();
So basically, an object is created from a class. In Java, the new keyword is used to create new objects. There are three steps when creating an object from a class − Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object.
To construct an object of type A you need to pass to the constructor either a reference to another object of type A, or else the null reference. So you have only two options:
A a1 = new A(null);
A a2 = new A(a1);
The first time you create an object of type A
you must use the null reference because you don't have any other objects of type A
.
Update
After you changed your question, I don't think it's possible to construct an object of type A
.
If I understand your question correctly, you want to create an object a without having to pass it a pre-existing object of the same type.
To do so you have to add a constructor to class A that does not take a parameter of type A or modify the existing one:
class A
{
A() {
// Constructor logic.
}
A(A a) {
// Constructor logic when passing an existing object of the same type, perhaps to create a clone.
}
}
If for some reason you can't modify class A, you'll have to follow Mark Byers' answer and pass a null reference to the constructor.
Update
With the update to your code, this problem (or thought experiment) is unsolvable: class A can not be instantiated as written.
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