java - 如何在java中创建一个动态全局变量
问题描述
您好,我是 java 新手,我想根据字符串条件创建一个变量,该变量将成为不同类的对象。我不知道该怎么做。
这是我要解释的
public class Foo {
Object obj; // I want this variable to be dynamic based on the condition in the constructor
public Foo(String str){ // Constructor
if(str.equals("bar")){
this.obj = new Bar();
}
else{
this.obj = new Baz();
}
}
我想要这样,因为稍后我将使用这个 obj 变量来调用 Bar 或 Baz 中的方法,它们都实现了同名但代码不同的方法。
解决方案
请检查此java代码,您将了解如何使用接口来解决此问题
package com.company;
public class Main {
public static void main(String[] args) {
Foo foo = new Foo("bar");
foo.obj.hello();
}
}
class Foo {
Ba obj;
Foo(String str) { // Constructor
if (str.equals("bar")) {
this.obj = new Bar();
} else {
this.obj = new Baz();
}
}
}
interface Ba {
void hello();
}
class Bar implements Ba {
public void hello(){
System.out.println(" Hello Bar");
}
}
class Baz implements Ba {
public void hello(){
System.out.println(" Hello Baz");
}
}
推荐阅读
- oracle - 选择结果表中显示的列 - Oracle(未按预期工作)
- powershell - PowerShell 从 Active Directory 中删除 ADGroup
- java - 如何删除泛型
来自Java中的PersonRepo? - favicon - 如何找到新标签页的图标?
- java - 错误:无法找到或加载主类 - 在提示符处运行 JAR 时
- c# - C# 组合框从数据库中动态添加多个项目文本和值
- java - 使用 AspectJ/Spring Boot 设置 Spring Tool Suite 4(缺少 m2e 连接器)
- python - 找不到 discord.py PILLOW 图像处理文件
- vb.net - 如何关闭 CefSharp 会话 winforms vb.net
- python - Python 类的问题