首页 > 解决方案 > 如何在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 中的方法,它们都实现了同名但代码不同的方法。

标签: javaoop

解决方案


请检查此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");
    }
}

推荐阅读