1

I'm working on a Java school project and I was wondering if I could instantiate a class but set its class type later on ?

I have two classes, Conference and ConferenceOnline. The latter is a subclass of Conference. Depending on a boolean, I want to create a new instance of ConferenceOnline if the boolean is true, else a new instance of Conference.

Here is an example:

boolean online = true;

if(online) {
  ConferenceOnline myclass = new ConferenceOnline();
}
else {
  Conference myclass = new Conference();
}

myclass.someMethod();

I could have instantiate the object before if/else but the fact that depending on online the object would not be created from the same class keeps me bugging.

I know it's not possible to create a variable inside an if statement and access it outside of the statement. Is there a way to do this except writing code inside the if else statement ?

  • take a look at this: https://stackoverflow.com/questions/1992384/program-to-an-interface-what-does-it-mean – Stultuske May 04 '22 at 17:04

1 Answers1

2

Since ConferenceOnline is a subclass of Conference (assuming someMethod is defined on Conference):

Conference myclass;
if (online) {
  myclass = new ConferenceOnline();
} else {
  myclass = new Conference();
}
myclass.someMethod();

Andy Turner
  • 137,514
  • 11
  • 162
  • 243