Question

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
Was it helpful?

Solution

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);
    }
}

OTHER TIPS

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, not string (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 () after 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. 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 class A and assigns the reference variable objA to it.
  • Also, objA.setvarA(name);. You missed semicolon here.
  • change your string to String. java is case sensitive.String is a class.
  • change this.varA=var.A; to this.varA = varA;
  • Missing semi colon here String name = "abc". Change to String 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); }

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top