Re: Difference Between Calling SuperClass Constructor or Inherited Set Method
crouse@physics.wm.edu wrote in news:1155583010.852503.219290
@h48g2000cwc.googlegroups.com:
Hello Everyone,
This is the situation. I have the usual base class w/ private instance
variable along with public methods manipulating them. I have a derived
class which inherits from the base class.
public class Base {
private int base;
Base() {
setBaseVar( 100 );
}
Base( int value ) {
setBaseVar( value );
}
public setBaseVar( int val ) {
base = val;
}
}
public classe Derived{
private int derived;
Derived( int derived ) {
super();
setDerivedVar( derived );
}
*Derived( int derived ) { // Alternative
setBaseVar( 100 )
setDerivedVar( derived );
}
setDerivedVar( int val ) {
derived = val;
}
}
Additionally, it is bad form to call an overridable method in a constructor
(base class or otherwise), because:
1. it is a potential security hole
2. it runs the risk (if you actually do override the method in the derived
class) of calling a method on an incompletely-constructed object, which is a
Very Bad Thing!
See "Effective Java" by Joshua Bloch for more information.
You can fix this by either making setBaseVar() final or by making it private.
If you make the method private, then you cannot call it from the derived
class, so it seems as if it would be better to just call super() in the
derived class' constructor.
Cheers
GRB
--
---------------------------------------------------------------------
Greg R. Broderick gregb.usenet200607@blackholio.dyndns.org
A. Top posters.
Q. What is the most annoying thing on Usenet?
---------------------------------------------------------------------