core - Object Creation in java and finalize -


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); // 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 line have commented, value of x shows 0(value of x in object ob), why isnt showing value of object o?? know if use o.x ll getting value of x in object o. still in code why show value of abject ob rather object o??

if want reference x in fdemo you've created, should add getx() function , call instead of x, david wallace said. (i prefer using getters instead of .variable).

add class:

public int getx(){     return x; } 

and change problematic line this:

system.out.println("creat obj no: " + o.getx()); 

that should fix it. side note, it's considered practice explicitly declare whether variables , methods private, public or protected.


Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -