Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested classes anonymous classes

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() ?

like image 356
nabil Avatar asked Jun 27 '26 10:06

nabil


1 Answers

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.

like image 118
jabal Avatar answered Jun 29 '26 23:06

jabal