Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a variable in constructor in a method outside of constructor

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?

like image 517
Drixy01 Avatar asked Dec 09 '22 19:12

Drixy01


2 Answers

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);
    }
}
like image 139
Rohit Jain Avatar answered Jan 05 '23 01:01

Rohit Jain


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; 
}
like image 37
y.ahmad Avatar answered Jan 04 '23 23:01

y.ahmad