Re: getting used to Java - question about "style"
From: Chris Smith (cdsmith_at_twu.net)
Date: 06/30/04
- Next message: Tim Ward: "Re: getting used to Java - question about "style""
- Previous message: glunk: "getting used to Java - question about "style""
- In reply to: glunk: "getting used to Java - question about "style""
- Next in thread: Tim Ward: "Re: getting used to Java - question about "style""
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Wed, 30 Jun 2004 07:00:15 -0600
glunk wrote:
> They go on to explain
>
> "Subclasses may override nonfinal methods and Java will dispatch a call to
> such a mrethod according to the actual type of the constructed object -
> before executing the derived class constructors. This means when the
> constructor invokes the derived method, the derived class may be in an
> invalid state. To prevent this, call only final methods from the
> constructor."
>
> I cannot understand what this says or means. I know that a final method is
> one that cannot be overridden. I do not understand what this parapgraph is
> intending to warn me against doing or why. Can someone explain, preferably
> with an example?
Sure:
public class A
{
public A()
{
init();
}
protected void init()
{
}
}
public class B extends A
{
private int var = 7;
public B()
{
}
protected void init()
{
System.out.println(var);
var = 42;
}
}
public class Main
{
public static void main(String[] args)
{
new B();
}
}
It's not obvious to most people that the code above prints "0" and not
"7", or that after the object has finished initializing, var will have a
value of 7 and not 42. Because this is confusing, you're advised to
avoid it. At the very least, if you do call a non-final (and non-
private, since private methods implicitly can't be overridden; and non-
static, since static methods aren't polymorphic) method from a
constructor, you should document this copiuously in the API docs for
that method, so people will know that they should not access any
instance state from that method.
-- www.designacourse.com The Easiest Way to Train Anyone... Anywhere. Chris Smith - Lead Software Developer/Technical Trainer MindIQ Corporation
- Next message: Tim Ward: "Re: getting used to Java - question about "style""
- Previous message: glunk: "getting used to Java - question about "style""
- In reply to: glunk: "getting used to Java - question about "style""
- Next in thread: Tim Ward: "Re: getting used to Java - question about "style""
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|