Reputation: 141
I always use constuctor only for attributes of one object. But i thin when i wrote this :
public Predmet(int esp,int obaveze,int cena){
this.cena=cena;
this.obaveze=obaveze;
this.esp=esp;
List j = new ArrayList();
j.add(8);
this.nesto=(int) j.get(0);
}
where are stored this ArrayList,does it part of object,or is on stack and have reference to array in heap?
Upvotes: 1
Views: 770
Reputation: 798
First, please don't use single variable names! This is bad practice and makes files harder to read. Using a more descriptive name helps to promote code readability.
The way that List j
is created, it only exists in the scope of the constructor. After your constructor, List j
is no longer accessible. If you wanted it to be accessible after the constructor, have a field for the object. For example:
public class Example {
private int specialNumber;
private List<Integer> numberList;
/**
* Constructs a new Example Object
*/
public Example(int exampleNum){
// specialNumber can be accessed from a Getter method (getSpecialNumber)
this.specialNumber = exampleNum;
this.numberList = new ArrayList<Integer>();
this.numberList.add(exampleNum);
// numberList is a field of this Example now
List<Integer> disappearingList = new ArrayList<Integer>();
disappearingList.add(exampleNum);
// After this method finishes, disappearingList will be gone
}
// disappearingList is no longer accessible
/**
* Gets this Example's specialNumber value
* @return int this.specialNumber
*/
public int getSpecialNumber(){
return this.specialNumber;
}
/**
* Gets this Example's numberList
* @return List<Integer> this.numberList
*/
public List<Integer> getNumberList(){
return this.numberList;
}
}
There is probably a way to hook into some of the Java cleaning methods and pull it out, but that will get a little messy. If you want to be able to create an Object inside another Object, and use it after the constructor, it must be saved as a field.
Upvotes: 0
Reputation: 237
Constructor is working very similar the way methods work. At runtime, anything you define inside constructor/method are called local variables. Their scope will end as soon as execution hits the end of the constructor/method. After consturctor, your list will be eligible for GC. However, this.nesto will still get value 8 as its primitive type.
Upvotes: 0
Reputation: 38132
The ArrayList is created on the heap and only referenced by the local variable j
from the stack here. After the execution of the constructor it will be eligible for garbage collection.
Upvotes: 2