Create Objects on Demand?

//I am looking for the preferred way
//to create objects on demand, during
//the execution of a program.
//Example: I have a program that works
//with objects known as a Marble. I want to
//create Marble objects with different names
//that I specify during the execution of the
//program. It seems to me that this would
//entering the name of the Marble from the
//keyboard into a String variable, and then
//using that variable to call the creation
//of a new Marble object. The problem is
//that the compiler balks about a duplicate
//variable. It seems logical that objects
//should be able to be created as needed,
//but how to do it? Thoughts?

Here is my example code:
--------------------Marble.java
public class Marble {
protected String size = null;
protected String color = null;

//Default Constructor
Marble(){
size = "small";
color = "blue";
}
}

-------------------MarbleController.java
import java.util.Scanner;

public class MarbleController {

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);

System.out.println("Enter a name for an Marble and press Enter");
String marbleName = keyboard.nextLine();

Marble marbleName = new Marble();
//The compiler balks when trying to use the variable "marbleName"
//as a placeholder for the entered name of a Marble object.
}
}

Comments

  • Variables can't be named at runtime.

    I think what you want to do is have a resizable array to which you can add Marbles.
    Then, to give the Marbles a unique name, add an extra name field to the object.

    [code]
    --------------------Marble.java
    public class Marble {

    protected String size;
    protected String color;
    protected String name;

    //Default Constructor
    Marble() {
    size = "small";
    color = "blue";
    name = null;
    }

    Marble(String name) {
    size = "small";
    color = "blue";
    this.name = name;
    }
    }

    -------------------MarbleController.java
    import java.util.Scanner;

    public class MarbleController {

    public static void main(String[] args) {

    List marbles = new ArrayList();

    Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter a name for an Marble and press Enter");
    String marbleName = keyboard.nextLine();

    Marble marble = new Marble(marbleName);
    marbles.add(marble);
    }
    }
    [/code]
  • Thanks for the insights. Using an data structure such as a List makes sense and is probably better than randomly making objects that would need to be kept track of by the user. Thanks!
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories