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);
}
}
How to use set method of a different class in java?
-
27-06-2022 - |
質問
How can I set the value of a parameter of class A
in class B
using the setvarA
method of class 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
解決
他のヒント
I'm surprised that you only complain about one error.
There are a number of different errors in the code you posted:
- It's
String
, notstring
(case is important) - In the method
setvarA
, this is wrong:this.varA = var.A;
, should have been:this.varA = varA;
- Forgot a semi-colon after
String name = "abc"
- Forgot
()
afternew 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. Add a main method in one of these files, creating B.
It should be A objA = new A();
- By doing this, you are invoking the constructor of class
A
which creates the object of classA
and assigns the reference variableobjA
to it. - Also,
objA.setvarA(name);
. You missed semicolon here. - change your
string
toString
. java is case sensitive.String
is a class. - change
this.varA=var.A;
tothis.varA = varA;
- Missing semi colon here
String name = "abc"
. Change toString name = "abc";
- You have put extra semi colon in setter method. Please correct that.
Also, you need to call the method from some init block or constructor or a method
B() { objA.setvarA(name); }
所属していません StackOverflow