0

I would like to ask something simple . I have created a class which will have a name. I want to create several of these classes , but the number of them is not exactly known. Every class has a unique name

What I want :

We have for example 3 classes, then their names should be:

Class #1

Class #2

Class #3.

I am thinking something like this:

for(int i = 0 ; i < numberofclasses ; i++ )
{
    C[i] = new Class("Class # **(i+1)** " );  (where i+1 , is the number of class)   
}

P.S. : any suggestions for better title are accepted

4
  • 1
    What is your question? Commented Feb 28, 2016 at 13:24
  • Do you want to dynamicaly load class ? Commented Feb 28, 2016 at 13:26
  • Are you looking for a way to load a class dynamically? Use "Class # "+(i+1) for the class name. Commented Feb 28, 2016 at 13:29
  • Doo you really want to create new Classes that way? Commented Feb 28, 2016 at 13:30

3 Answers 3

1

This is my preferred way. I don't like the + because it can also be used for mathematical operations.

// Call String.format with three integer codes.
String result = String.format("One: %1$d Two: %2$d Three: %3$d",10, 20, 30);
System.out.println(result);
Sign up to request clarification or add additional context in comments.

Comments

0

Interpreting your question as you actually have several compiled classes with predictable names.

You'll have to use reflection of some sort to load and create instances of the classes.

For example:

Class.forName("ClassName").newInstance();

This assumes your class has a constructor without arguments.

Comments

0

Thanks everyone for the suggestions , the answers that worked for me was :

adding +(my int) after strings

System.out.println("Class #"+(i+1)) 

(fast solution )

and @Moua Li's answer:

String result = String.format("One: %1$d Two: %2$d Three: %3$d",10, 20, 30);
System.out.println(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.