Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: why "this( )" is not overriden?

See below example:

class A {
   A() { this(1); }
   A(int i) { System.out.println("A" );  }
}

class B extends A {
    B() {}
    B(int i) {  System.out.println("B" );  }
}

public class Test
{
    public static void main(String[] args)   {        
       A o =  new B();
    }
}

The output:

A

Q1:Seems java does not perform late binding for "this(1)". It has been decided at compile-time.Please confirm.

Q2:Java does not perform late binding on any constructors. Please confirm.

Q3:Does this mean constructors are implicitly final?

like image 767
Don Li Avatar asked Dec 26 '22 23:12

Don Li


1 Answers

You cannot override constructors. They don't follow inheritance rules at all. They can't follow inhertitance rule because you need a simple order for constructing your object.

e.g. in your example, if you could override the A(int) constructor A() would call B(int), but B(int) implicitly calls super() which is A() and you have infinite recursion.

It is often considered bad practice for a constructor to call an overrable method. So having constructors do this automatically would be a very bad idea.

If the constructors were final, like static final methods you wouldn't be able to hide them either, but you can, so I would say they are final either.

like image 156
Peter Lawrey Avatar answered Jan 05 '23 21:01

Peter Lawrey