我有两个类(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/