[英]How to use set method of a different class in java?
How can I set the value of a parameter of class A
in class B
using the setvarA
method of class A
? 如何设置类的参数值
A
类B
使用setvarA
类的方法A
?
public class A{
String varA;
public String getvarA() {
return varA;
}
public void setvarA(String varA) {
this.varA=varA;
}
}
public class B{
String name = "abc";
A objA = new A();
objA.setvarA(name) ; ## THIS LINES THROWS AN ERROR
}
The error is: 错误是:
Syntax error on token "name", VariableDeclaratorId expected after this token and Syntax error on token(s), misplaced constructs
public class A{
String varA;
public String getvarA() {
return varA;
}
public void setvarA(String varA) {
this.varA=varA;
}
}
class B {
String name = "abc";
A objA = new A();
B() {
objA.setvarA(name);
}
}
I'm surprised that you only complain about one error. 我很惊讶您只抱怨一个错误。
There are a number of different errors in the code you posted: 您发布的代码中存在许多不同的错误:
String
, not string
(case is important) String
,不是string
(大小写很重要) setvarA
, this is wrong: this.varA = var.A;
setvarA
,这是错误的: this.varA = var.A;
, should have been: this.varA = varA;
this.varA = varA;
String name = "abc"
String name = "abc"
后忘记分号 ()
after new A
: A objA = new A();
new A
之后忘了()
: A objA = new A();
Revised Code: 修改后的代码:
public class A{
String varA; //<-String, not string
public String getVarA() {
return varA;
}
public void setVarA(String varA) {
this.varA=varA; //<- var.A not valid
}
}
class B{
B(){ //<- Need to write this code in a method or constructor
String name = "abc"; //<- Semi-colon?
A objA = new A(); //<- what about parenthesis?
objA.setVarA(name); //<- Semi-colon?
}
}
Here's the corrected and complete code: 这是更正和完整的代码:
public class A{
String varA;
public String getvarA() {
return varA;
}
public void setvarA(String varA) {
this.varA = varA;
}
}
public class B{
public B(){
String name = "abc"
A objA = new A();
objA.setvarA(name);
}
}
Both classes must go in separate files, calles A.java and B.java, of course. 当然,这两个类都必须放在单独的文件中,分别称为A.java和B.java。 Add a main method in one of these files, creating B.
在这些文件之一中添加一个main方法,创建B。
It should be A objA = new A();
应该是
A objA = new A();
A
which creates the object of class A
and assigns the reference variable objA
to it . A
它创建类的对象A
和参考变量分配objA
它 。 objA.setvarA(name);
objA.setvarA(name);
. string
to String
. string
更改为String
。 java is case sensitive. String
is a class. String
是一个类。 this.varA=var.A;
this.varA=var.A;
to this.varA = varA;
this.varA = varA;
String name = "abc"
. String name = "abc"
。 Change to String name = "abc";
String name = "abc";
Also, you need to call the method from some init block or constructor or a method 另外,您需要从一些init块或构造函数或方法中调用该方法
B() { objA.setvarA(name); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.