Anthony
Anthony

Reputation: 4050

Accessing an Object from other Methods

How do I access an object, that was instantiated in the constructor, in another method? (e.g. object b below) What is the best way to instantiate this object so that all of my class methods have access to the same object?

public class ClassA{ 
  private final int size;       

  public ClassA(int N){
      size = N;    
      ClassB b = new ClassB(size);
  }

  public void doSomething(){
      b.doSomething();        
  }      
}

Upvotes: 0

Views: 84

Answers (4)

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26727

you can simply create a property/field of type B

public class ClassA{ 
  private final int size;       
  private B bInstance;

  public ClassA(int N){
  size = N;    

  bInstance = new ClassB(size);
  }

  public void doSomething(){
  b.doSomething();        
  }      
}

Upvotes: 2

David M
David M

Reputation: 72860

Declare it as a field just as you have done with size:

public class ClassA{ 
  private final int size;   
  private final ClassB b;    

  public ClassA(int N){
    size = N;    

    b = new ClassB(size);
  }

  public void doSomething(){
    b.doSomething();        
  }      
}

Upvotes: 2

Keppil
Keppil

Reputation: 46209

You just need to assign it to a field:

public class ClassA{ 
  private final int size;       
  private final ClassB b;

  public ClassA(int N){
    size = N;    
    b = new ClassB(size);
  }

  public void doSomething(){
    b.doSomething();        
  }      
}

Upvotes: 5

kosa
kosa

Reputation: 66637

Define ClassB b as instance variable.

public class ClassA{ 
  private final int size;       
 ClassB b;
  public ClassA(int N){
  size = N;    

  b = new ClassB(size);
  }

  public void doSomething(){
  b.doSomething();        
  }      
}

Upvotes: 2

Related Questions