public class A {
protected int x;
public A(int x) { this.x = x; }
public void g() { System.out.println(x); }
public void h() { System.out.println(x + 10); }
}
public class B {
public void f() {
(new A(2) {
public void g() {
h();
}
}).g();
}
}
public static void main(String[] args) {
new B().f();
}
Can some body help me understanding this line in code:
new A(2) { public void g() {h();} }).g();
I don't understand if he define a anonymous class here with A ?? and how in the anonymous he can refer to A.h() ?
This line creates a no-named class that overrides the parent class's g() method so that it does a new thing: invoking h(). However at once it calls the g() method on this no-named class at once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With