0

Let's say I have a class:

class A {
    public A fun() {
        System.out.println("a");
        return this;
    }   
}

And a scenario:

A a = new A();
a.fun().fun().fun().fun();
a.fun().fun();

Is it somehow possible to print additional message in the first call of each sequenced calls without adding something like .start()/.finalize()?

xinaiz
  • 7,744
  • 6
  • 34
  • 78

1 Answers1

4

You could do something like this:

public class A {

    public A fun() {
        System.out.println("A");
        return new AA();
    }

    private class AA extends A {
        @Override
        public A fun() {
            System.out.println("AA");
            return this;
        }
    }

    public static void main(String[] args) {
        A a = new A();
        a.fun();
        a.fun().fun();
        a.fun().fun().fun();
    }
}

Outputs:

A
A
AA
A
AA
AA
Kenster
  • 23,465
  • 21
  • 80
  • 106