eg.
abstract MySuperCalss {
Logger log someLogger;
public void mymethod() { }
}
MySubClass extends MySuperClass {
publlic void someMethod{
someLogger.info("Hello");
}
if I don't take care to instanticate someLogger, it will throw
NullPointerException in MySubClass.someMethod();
I can't define someLogger as abstract neither.
note that I can have many subclasses, so making a just a mental note to
set it in every subclass is not good enough. I'd like the compiler
to catch it.
thanks
j.
shakah - 07 Nov 2005 18:47 GMT
jlu...@gmail.com wrote:
> eg.
>
[quoted text clipped - 19 lines]
> thanks
> j.
the following:
public class MySuper {
Logger l_ ;
public MySuper(Logger l) {
l_ = l ;
}
}
would force your subclasses to at least consciously set the logger,
e.g.:
// ...produces a compilation error
public class MySub : extends MySuper {
public MySub() {
}
}
// ...requires syntax like:
public class MySub extends MySuper {
public MySub() {
super(new Logger()) ;
}
}
// ...or
public class MySub extends MySuper {
public MySub(Logger l) {
super(l) ;
}
}
// ...etc.
Rhino - 07 Nov 2005 18:51 GMT
> eg.
>
[quoted text clipped - 19 lines]
> thanks
> j.
If it were my program, I would pass the logger to the constructor of the
subclass so that it is available to the subclass's method when it is needed.
Any code that instantiate the subclass would then have to supply a value for
the Logger or it would cause a compiler error.
Now, the value passed in the statement that instantiates the subclass could
pass a null value for the Logger and that would satisfy the compiler. I
would deal with that problem by checking the Logger value in the constructor
of the subclass; if it is null, throw an IllegalArgumentException. That, of
course, is a runtime error, not a compile error, but I don't know of any
better solution.
Rhino
Oliver Wong - 07 Nov 2005 20:50 GMT
> note that I can have many subclasses, so making a just a mental note to
> set it in every subclass is not good enough. I'd like the compiler
> to catch it.
shakah gave a good solution. Here's an alternative:
<code>
abstract class MySuperClass {
protected abstract Logger getLogger();
}
class MySubClass extends MySuperClass {
private Logger myLogger = new Logger();
public void someMethod{
this.getLogger().info("Hello");
}
protected Logger getLogger() {
return this.myLogger;
}
}
</code>
The abstract getter is usually a good reminder for implementors of
subclasses that they MUST create a logger.
- Oliver