StarSweeper StarSweeper - 25 days ago 5
Java Question

Is it possible to declare an object of either one class or another in Java?

Newbie here. Part of my assignment is to ask the user which of two categories their incoming phone call belongs in.

class CategoryA and class CategoryB are both inherited from the class PhoneCall which we made in a previous assignment.

I want to do this:

String choice = null;
System.out.printf("Please enter a 'A' for Category A%n");
System.out.printf("Please enter a 'B' for Category B%n");

//[Input validation/exception handling stuff goes here]

case "A":
CategoryA objectName = new CategoryA();
case "B":
CategoryB objectName = new CategoryB();

But of course that doesn't work because

  1. I'm declaring objectName inside the switch statement so I can't use it outside of it.

  2. Both the objects have the same name (even though only one of them would be declared).

The rest of the program uses objectName. If I have to have two different object names then I have to have a if/else statements or switch statements every single time I would have used objectName, right? I can't even pass the object to a function because its either of one class or the other. Is there some solution I am missing here?

Notes: (CategoryA and CategoryB have to be inherited from PhoneCall because that is the whole point of the assignment.)


So what you want to use is something called polymorphism. That's when you declare an object of a parent class (or interface), but initialize it as a subclass.

For example, if you have an interface A, with subclasses B and C, doing this:

InterfaceA obj;
    obj = new ClassB(parameters);
} else {
    obj = new ClassC(parameters);

will create either a Class B or C. Because they are listed under a parent class, you can only call methods that the parent class has. In other words, if Class B has a unique method, you can't call that unless you cast the object as that type:

ClassB objB = (ClassB) obj;

However, this throws an error if obj isn't a ClassB, so you first need to check if obj is a ClassB:

if(obj instanceOf ClassB){
    ClassB objB = (ClassB) obj;

That way you make sure that you can cast obj to a ClassB before you do it.

This works for either interfaces or classes.