Assignment in anonymous inner class Java -
here have class contains anonymous inner class:
public class example { int value; example(int value) { this.value = value; } void bumpup() { value++; } static example makeexample(int startval) { return new counter(startval) { int bumpvalue = 2; // value = startval; void bumpup() { bumpvalue = (bumpvalue == 2) ? 1: 2; value+= bumpvalue; } }; } }
if uncomment line says value = startval
, eclipse throws error saying above line error. why can't put value = startval
there?
thanks!
first of all, putting line there syntax error, because cannot have instructions outside of method. , you're attempting put instruction within body of anonymous inner class.
but above all, don't need line, neither in constructor (which impossible anonymous inner class), nor in initializer block.
the constructor of superclass automatically invoked when constructing anonymous inner class instance, , startval
passed along constructor of example
, it's assigned attribute value
.
finally, new counter(startval)
doesn't make sense (where's counter
class)? believe it's either copy-paste error, or have counter
class declared somewhere else. in latter case, counter
should extend example
, or you'd compilation error.
here's code fixes:
public class example { int value; example(int value) { this.value = value; } void bumpup() { this.value++; } static example makeexample(int startval) { return new example(startval) { int bumpvalue = 2; @override void bumpup() { this.bumpvalue = (this.bumpvalue == 2) ? 1 : 2; this.value += this.bumpvalue; } }; } public static void main(string[] args) { example = example.makeexample(7); system.out.println(a.value); a.bumpup(); system.out.println(a.value); a.bumpup(); system.out.println(a.value); a.bumpup(); system.out.println(a.value); a.bumpup(); system.out.println(a.value); a.bumpup(); system.out.println(a.value); } }
this prints:
7 8 10 11 13 14
Comments
Post a Comment