3

Lets assume I have class:

class A {
    protected int x; // no public getter, setter
}

Now I want to extend class A, to overwrite 'x' variable. The answer would be:

public class SomeClass {
    someMethod() {
        A extendedClass = new MyExtension(5);
    }

    class MyExtension extends A {
        public MyExtension(int x) {
            super.x = x;
        }
    }
}

And my question: is there any possibility to do it without defining nested class separately? I mean something like this

    someMethod() {
        A extendedClass = new A() {
            // here do something like super.x = 5;
        }
    }

I tried with Calling newly defined method from anonymous class but it won't let me instantiate A class. Also I dont want to use reflection.

I simpy dont want to define nested class just to overwrite one property. Origin of the problem is Spring-integration ImapMailReceiver, where I want to overwrite task scheduler. Like below:

    final ImapMailReceiver imapMailReceiver = new ImapMailReceiver() {
           super.setTaskScheduler(MYTASKSCHEDULERHERE);
    }
gmarczyk
  • 31
  • 2

2 Answers2

2

Your new A() { ... } still is just defining a new class. Thus, you cannot simply put any statement between the curly brackets, only field, method and nested type declarations may go there, but constructors are not allowed. You may add an instance initializer instead:

A extendedClass = new A() {
  {
    x = 5;
  }
}
Amadán
  • 718
  • 5
  • 18
0

Why to use nested or anonymous inner class? We can do overriding and access the overrided variable as below.

public class SomeClass extends A{
    int val;
    void someMethod(int val) {
        super.x = val;
    }

    public static void main(String[] args) {
        SomeClass sc = new SomeClass();
        System.out.println(sc.x);  // output=10
        sc.someMethod(20);
        System.out.println(sc.x);  // output=20
    }

}
class A {
    protected int x = 10; // no public getter, setter
}
madhepurian
  • 271
  • 1
  • 13