我如何声明新课程,但要设置其类“类型”类别。之后?

发布于 2025-01-26 08:42:44 字数 684 浏览 0 评论 0原文

我正在研究 Java 学校项目,我想知道我是否可以实例化课程,但以后将其类型设置为?

我有两个类, 会议 conferitionOnline 。后者是 会议 的子类。根据布尔值,我想创建一个新实例 conferenceOnline 如果布尔值是真实的,则是 会议>会议>的新实例

这是一个示例:

boolean online = true;

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

myclass.someMethod();

如果/否则,我可以在对象之前实例化对象,但根据 在线 的事实,该对象不会从同一类中创建对象使我感到困惑。

我知道不可能在if语句中创建一个变量并在语句之外访问它。除了在if else语句中编写代码外,有没有办法这样做?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

青朷 2025-02-02 08:42:44

由于conferenceOnline会议的子类(假设somemethod是在会议>会议上定义的):

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

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();

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文