-2
class FDemo { 
    int x; 

    FDemo(int i) { 
        x = i; 
    } 

    protected void finalize() { 
        System.out.println("Finalizing " + x); 
    } 

    void generator(int i) { 
        FDemo o = new FDemo(i); 
        System.out.println("Creat obj No: " + x); // this line
    } 

} 

class Finalize { 
    public static void main(String args[]) { 
        int count; 

        FDemo ob = new FDemo(0); 

        for(count=1; count < 100000; count++) 
            ob.generator(count); 
        } 
    }
}

In the line i have commented, the value of x always shows 0(value of x in object ob), why isnt showing the value of object o?? i know if i use o.x i ll be getting the value of x in object o. But still in this code why does it show the value of abject ob rather than object o??

Loktopus
  • 462
  • 2
  • 12
Sunil
  • 29
  • 7
  • Erm, you instantiate a new `FDemo` then discard it without doing anything with it. What exactly do you expect to be happening? – Brian Roach Apr 24 '14 at 02:22
  • You haven't told it to look in `o` for `x`. If you write `System.out.println("Create obj No: " + o.x);` you'll get what you expect, but `x` by itself refers to `x` in the current object, not `x` in the object that you just created. – Dawood ibn Kareem Apr 24 '14 at 02:22
  • If you change 'int x' to 'static int x' it should be work, but your approach is wrong. If you will change the value from the object create setter method insted of creating a new instance. – franki3xe Apr 24 '14 at 02:30
  • @franki3xe That will get him the output he's looking for, but it will change the value of x for all of his FDemo objects. Because he sets this in the constructor, I'd assume he wants it to be different for each object. – Loktopus Apr 24 '14 at 02:32

1 Answers1

0

If you want to reference the x in the FDemo you've just created, you should add a getX() function and call that instead of x, like David Wallace said. (I prefer using getters instead of .variable).

Add this to your class:

public int getX(){
    return x;
}

And change your problematic line to this:

System.out.println("Creat obj No: " + o.getX());

That should fix it. As a side note, it's considered good practice to explicitly declare whether your variables and methods are private, public or protected.

Loktopus
  • 462
  • 2
  • 12