Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 访问运行时设置的变量值_Java_Oop - Fatal编程技术网

Java 访问运行时设置的变量值

Java 访问运行时设置的变量值,java,oop,Java,Oop,以下是场景: 我有三个类:类A、类B和类C。现在我调用一个在C中定义的方法,在类A中使用返回类型字符串。我将返回值设置为类A中的另一个字符串。现在在类B中,我创建一个类A的对象,并使用该对象调用在A中设置的字符串。如果您想知道执行情况,那么首先我在a中调用C中定义的方法,然后在B中调用字符串。但是我在B类中得到的字符串值为空 C类 Class C{ //method with return type as string public String getString(){ retur

以下是场景:

我有三个类:类A、类B和类C。现在我调用一个在C中定义的方法,在类A中使用返回类型字符串。我将返回值设置为类A中的另一个字符串。现在在类B中,我创建一个类A的对象,并使用该对象调用在A中设置的字符串。如果您想知道执行情况,那么首先我在a中调用C中定义的方法,然后在B中调用字符串。但是我在B类中得到的字符串值为空

C类

Class C{
 //method with return type as string
 public String getString(){
    return "Some String Here";
  }
}
甲级

Class A{
public String s;
public void somemethod(){
C obj = new C();
s= obj.getString();
  }
}
B类

Class B(){
pubic void anothermethod(){
A obj = new A();
String ss = obj.s;
}
}
ss在打印时将null作为其值。当我打印s时,我得到了正确的字符串。这是我在主课上打电话的方式

  • 类A中的方法somemethod()
  • 2.然后是类B中的anothermethod()方法


    抱歉,如果我的问题有点不着边际。

    如果您的问题是关于如何在
    ss
    中获取空值,您从未在
    anothermethod
    中调用
    obj
    上的
    somemethod
    。每次调用
    anothermethod
    ,您都会实例化一个新的
    a
    ,其中字符串字段
    s
    从未初始化,仍然为空。

    这里是一个工作版本。见评论:

    class A{
    
        private C c;
        public void somemethod(){
            c = new C();//better put is A constructor 
        }
        public String getS() {
            return c.getString();
        }
    
        public static void main(String args[]) {
            new B().anothermethod();
        }
    }
    
    class B{
    
        public void anothermethod(){
            A a = new A(); //better put is B constructor 
            a.somemethod();
            System.out.println( a.getS()); //output: Some String Here
        }
    }
    
    class C{
    
        //method with return type as string
        public String getString(){
            return "Some String Here";
        }
    }
    

    谢谢你的解释。对不起,我没有什么好怀疑的。