Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an object of this class?

Tags:

java

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.
     }
  }
like image 935
Ice Box Avatar asked Jun 02 '12 10:06

Ice Box


People also ask

Can we create object of class in Java?

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.

How do you create an object object in Java?

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.

Which is the correct way to create an object of a class in Java?

Using new Keyword The new keyword is also used to create an array. The syntax for creating an object is: ClassName object = new ClassName();

What is an object and how do you create it?

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.


2 Answers

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.

like image 118
Mark Byers Avatar answered Sep 22 '22 08:09

Mark Byers


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.

like image 26
Lilienthal Avatar answered Sep 19 '22 08:09

Lilienthal