Why does Java require that the first line constructor should call the parent constructor? If we bypass this requirement, are there any traps?

I have the next code:

class Foo {

   public Foo (String param) { ... }
}

class Bar extends Foo {

   public Bar () {
      super (doSmth());
      ...
   }

   private static String doSmth () {
      //what I can NOT do here?
   }
}

I wonder if it's safe? Are there any restrictions on the dosmm method?

Solution

The simple rule is not to access the "this" object directly or indirectly from the constructor

This means that you should not call the rewritable method from the constructor, nor call the method of invocable rewriting, or invoke the method of invocation of the rewriting method, or... You see.

It also means that you shouldn't pass "this" to anything because another thing can call a rewritable method

In your special situation, what is good for you If you want to change to:

class Bar extends Foo 
{
    public Bar () {
        super (doSmth(this));
        ...
    }

    private static String doSmth (Bar bar) {
        //what I can NOT do here?
   }
}

Then you have a potential problem, because doSmth can invoke a override method that relies on uninitialized data in the subclass of Bar.

The following is an example of what might happen:

public class Main
{
    public static void main(final String[] argv)
    {
        final A a;

        a = new B();
        a.foo();
    }
}

abstract class A
{
    protected A()
    {
        bar(this);
    }

    private static void bar(final A a)
    {
        a.foo();
    }

    public abstract void foo();
}

class B extends A
{
    final String str;

    public B()
    {
        super();
        str = "Hello,World!";
    }

    public void foo()
    {
        System.out.println("str - " + str);
    }
}

So, as long as you don't call any overridden methods, you are good However, the safest way is to follow the rules, that is, never transmit it outside the constructor, nor directly or indirectly call the rewritable (non final) method from the constructor.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>