java - 从类 B 访问类 A 中的公共(public)方法时出现问题

标签 java class methods

我有两个类(class),A类和B类。

public class A {
    B testB = new B();
    testB.setName("test"); //**Error Syntax error on token(s), misplaced constructs
                           //**(same line above) Error Syntax error on "test"
}

//in a separate file
public class B {
    public String name;
    public void setName(String name){
        this.name = name;
    }
}

为什么我无法在A类中访问B类中的这个函数“setName”?谢谢。

最佳答案

您需要从另一个方法或构造函数中调用该函数。

    public class A {

      //Constructor
      public A(){
        B testB = new B();
        testB.setName("test");
      }

      //Method
      public void setup(){

        B testB = new B();
        testB.setName("test"); 
       }
    }

    /*Then in a main method or some other class create an instance of A 
and call the setup method.*/

    A a = new A();
    a.setup();

关于java - 从类 B 访问类 A 中的公共(public)方法时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13281023/

相关文章:

java - 将 javabean 的图形序列化为 xml,每个 java 实例都有单独的 xml 文件

actionscript-3 - 类之间的命名空间变量

java - 如何读取作为命令参数的文本文件(字符串)的第一行(在Java中使用eclipse)

c# - 在类和方法之间共享变量

c++ - 从类 A 到类 B 的方法的空指针

java - Android - 如何从另一个类更新 textview

java - 使用值对 map 进行排序的最佳方法

java - 如何将所有按钮放在同一行?

c++ - 声明所有类 C++ 访问的全局变量

php - 可以存在在 php 上加载动态类的最佳实践/方法吗?