Why does java have a requirement that the first line of the constructor call the parent constructor? Are there pitfalls if we get around this requirement?

I have the following 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?
   }
}

Interestingly, is it safe? Are there any restrictions on the method doSmth?

+3
source share
5 answers

A simple rule is direct or indirect access to the "this" object from the constructor.

This means that you should not call overridden methods from the constructor, and you should not call a method that calls an overridable method, or call a method that calls a method that calls an overridable method, or ... you get an idea.

, "this" -, .

. :

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

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

() , doSmth overriden Bar, , .

, :

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);
    }
}

, , - , . "" ( ) , , .

+4

, , . . Java ( )

class Foo { 
  string m_field;
  public Foo(string param) {
    m_field = param;
  }
  public void Method() {
    // use m_field
  }
}

class Bar extends Foo { 
  public Bar() {
    // no super
    Method();  // oops
  }
}
+3

, - ...

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

, . , . /.

, super():

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

... doSmth() , .

+3

. :

class MyImplementation extends SuperImplementation {
   public MyImplementation(String input) {
      super(convertInput(input));
      ...
   }

   private static String convertInput (String input) {
      String output = "";
      // do something with input and put it to output
      return output;
   }
 }
+1

java , ?

, , Java ,

class Foo(){
abc()
this()

}

class Foo(){
this()
abc()
this()

}

http://www.leepoint.net/notes-java/oop/constructors/constructor.html

( ), ( ). , .

0
source

Source: https://habr.com/ru/post/1752687/


All Articles