Re: Extend a class without calling the constructor



kebabkongen@xxxxxxxxxxx wrote:
I wish to override a method of a class A (I cannot alter class A)
I plan to do this by creating a class B which extends A, and overrides
the method.
When implementing class B, I cannot compile unless I create a
constructor in class B which calls super(<params>)
The problem is that super(<params>) calls the method I wish to
override, and with the given parameters throws an exception...

Constructors calling (virtual) methods are bad (though not as bad as in C++). Best avoided.


If you really, really have to then make the overriding method correct even before you constructor has executed. There are hacks with thread-locals, synchronised statics or inner classes (with -target 1.4 or greater) to hand context information over.

Is there someway to extend a class without calling the constructor of
the class being extended?

You could rewrite the bytecode of A. Possibly if it is Serializable, you could hack around the constructor calling the method, but the method would probably get called during deserialisation anyway.


Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/
.



Relevant Pages

  • Re: Do some computation before calling super constructor.
    ... Imagine that a subclass overrides a ... method used in the constructor. ... fields in the subclass that have not yet been initialized. ...
    (comp.lang.java.help)
  • Re: Constructor Chaining Conundrum
    ... that is not overriden by the child. ... s in Derived *shadows* s in Base, ... printin Derived *overrides* printin Base; ... constructor calls print, Derived's printwill be called (we are ...
    (comp.lang.java.programmer)
  • Re: Can a classs constructor call another constructor "later"?
    ... I find the current constructor behaviour ... with "constructor overrides behave in the opposite way to method ... choose to call the base method wherever you like, ... I should point out that what Alex did in his first example ...
    (microsoft.public.dotnet.csharp.general)