4

if i have a constructor like so:

    public Constructor (int a, int b){

        int c =  a;
        int d =  b; 
    }

How can i then use variable c and d in a method within the same class as the constructor because trying to use just the variables name in the method doesn't seem to work?

4
  • 3
    int c = int a; will not compile, you need int c = a; Commented Nov 21, 2012 at 18:58
  • after fixing what I said before, you can pass them as parameters to your methods (from within your constructor) or save the values in instance attributes and use them in the method. Commented Nov 21, 2012 at 19:00
  • not sure why this was down voted, seems like a valid question to me. Commented Nov 21, 2012 at 19:01
  • 1
    it's not sscce? Commented Nov 21, 2012 at 19:06

2 Answers 2

13

In fact your code will not compile - int c = int a is not valid.

I assume that you meant: - int c = a;.

How can i then use variable c and d in a method within the same class as the constructor

You can't because you have declared them as local variables whose scope ends when the constructor ends execution.

You should declare them as instance variables.

public class MyClass {
    int c;
    int d;

    public MyClass(int a, int b){

        this.c = a;
        this.d = b; 
    }

    public void print() {
        System.out.println(c + " : " + d);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Tried to fix a syntax error and got rolled back. Make sure you keep it next time you edit :)
Yeah I just removed the 2nd ints (on the right hand side of the assignment in the constructor). It looks good now.
What's the difference in that case between using this.c = a and c = a?
1

You need to declare the variables as class members, outside the constructor. In other words, declare c and d outside of the constructor like so:

int c;
int d;

public Constructor (int a, int b) {

        c = a;
        d = b; 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.