mishkapp
mishkapp

Reputation: 79

How to put variable from constructor to method?

I have code like this:

public class Class1 {

    public void method1() {
        ...
        Class2 c = new Class2(i);
        ...
    }

    public Class1(int i) {
        ...
    }
}

How can I get variable i from constructor to method1 ?

Upvotes: 0

Views: 95

Answers (3)

cowls
cowls

Reputation: 24334

You need to declare a field in the class. E.g.

private int i;

Then in the constructor set this.i = i; You can then access i from anywhere in the class.

To be honest this is pretty basic stuff so Id suggest reading up on Java basics before continuing a project :)

Upvotes: 2

stacker
stacker

Reputation: 68962

Use member variable i to store the value

public class Class1 { 
  private int i;

  public void method1 () { ... 

   Class2 c = new Class2(i); 
    ... } 

   public Class1 (int i){ 
       this.i = i;
... 
}} 

Upvotes: 2

talnicolas
talnicolas

Reputation: 14053

You can put i as an instance variable.

public class Class1 {

    private int i;

    public void method1 () {
       ...
       Class2 c = new Class2(i);
       ...
    }
    public Class1 (int num){
        this.i = num;
    }
}

Upvotes: 2

Related Questions