I want to do something like this:
Creator method = new Creator();
method.addSubject("example");
class Creator{
public void addSubject(String subjName) {
//here is the issue
subjName = new Subject(subjName);
}
}
class Subject {
private String name;
public Subject(String newName) {
name = newName;
}
}
So I want this class called Creator to be able to make Subjects, but I need it to be able to do so by passing it a String with the name that I want to call those subjects. How can I do this?
Edit: To clarify, the class “Creator” has a method called “addSubject”. In the main method of the program I have an object of Creator called “method” (probably should have chosen a better example name). So can this object of Creator make objects of another class, class “Subject”, simply by passing the method “addSubject” the name I want those objects of Subject to have?
Edit2: This is the pseudocode of what I want:
Main method:
Initialize Creator object
Command line for program takes arguments
Pass these arguments to creator object
Creator Object:
Takes command line argument in the form of string and makes a new object of the class Subject by the name of the String
I think you want to create a new object of a class that you just want to use the name. Is it? So, you can do this (Java 7).If you are using a Java version prior to 7, you need to use 3 catch statements, one for ClassNotFoundException, one for IllegalAccessException and one for InstantiationException.
Edit: I think I understood now. You want to create instances of Subject with a name passed to the method. You can use a HashMap to simulate this.
Something like: