简体   繁体   中英

dynamically creating object [java]

This might be a simple question to answer but I am new to programming. My question is how do I create an instance of a class dynamically. For example I have a circle class which has methods of calculate area and half area and so on and the classes constructor initialises all the class fields like the radius and other fields. What I want to be able to do is create an instance of the class whenever a user wants to create a new circle. To create a circle class this is what I currently have

circle c1 = new circle(radius);

but this object is statically created when I write the code, so how can I create a new instance of a class when a user wants to create a new object.

Thank you for any help in advance. Please be nice new to programming.

Have a look how simple it could be

 Circle c1 ;
 //{
    // your users wish and store it in some boolean var .
 //}

 if (userWantsObjectCreation) {
       c1 = new Circle();
 }
 else {
    // your holy logic here instead if object creation .
 }

You can take input from user asking for "create circle? enter Y or N" and then use if else condition

if("Y".equals(input))
{
c1 = new Circle();
}

else{
//something else
}

Basically, you have to store all the created circles in a "list" structure.

For example:

List<Circle> list = new ArrayList<Circle>();

Circle c1 = new Circle(radius);
list.add(c1);

...

void onUserClickedCreateCircle() {
    Circle c = new Circle(15);
    list.add(c);
}

void renderAllCirclesOnScreen() {
    //Take each circle from the list into variable c
    for (Circle c : list) {
        drawCircle(c);
    }
}

The syntax as the following:

ObjectName obj=Class.forName("object name full name").newInstance();

For example, you have class named Car, which is resided in com.toyota package. Then you can instantiate Car object using the following statement:

Car car=(Car)Class.forName("com.toyota.Car").newInstance(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM