I am creating a simple, text-based interactive application, where the user is prompted for input. Each input corresponds to a specific command, which invokes a certain method. Because there are many methods, I have chosen to distribute them between different classes. So the application works like this:
The main class is responsible for reading the user input (using a Scanner object). The user input is then passed as a parameter to a method B in class B that decides which command the input corresponds to. After deciding, the method invokes the correct method, which can be in any of the other classes (in this example, method C in class C)
This means that I have to initialize object instances in order to avoid null pointer exception. One of the classes that I have to initialize an object from only has a constructor with parameters, but I don't actually want to initialize an object with values in this case, but only to use it as a reference pointer to the object so I can invoke methods from that class. Now I am using an empty constructor in order to solve this, but is there any alternative, better solution than declaring an empty constructor? I have written code that I think demonstrates my problem:
public class MainClass {
ClassB classB = new ClassB();
public void methodA {
classB.methodB(userInput);
}
}
public class ClassB {
ClassC classC = new ClassC();
public void methodB {
classC.methodC();
}
}
public class ClassC {
String name;
int age;
public ClassC(String name, int age) {
this.name = name;
this.age = age;
}
public ClassC() {
}
public void methodC() {
// Do something
}
}