简体   繁体   中英

Overloading a class containing an explicit constructor with a call to super ( )

It appears that if a programmer supplied constructor, with a call to super ( ) is used, no other constructor can be invoked in that class ( ie it can't be overloaded). Is this normal behavior that is inherent to Java? Why?

abstract class Four {
     Four (  ) { }
     Four (int x) { }
    }
class Three extends Four  {
    public Three ( String name) { }
    Three (int t, int y) { }
    }
class Two extends Three {
    Two ( ) { super ( "number");  } 
//  Two (int t, int y) { }  //causes an error when uncommented
    }
class One extends Two {
    public static void main (String [ ] args) {
        new One ( ); 
        }
    }

no other constructor can be invoked in that class ( ie it can't be overloaded).

That's not true at all. The problem with your Two(int t, int y) constructor is that it doesn't chain to any constructor explicitly, meaning that there's an implicit super() call - which fails as there are no parameterless constructors in Three 1 . You can fix that in two ways:

  • Chain directly to a super constructor

     Two (int t, int y) { super("number"); } 
  • Chain to a constructor in the same class

     Two (int t, int y) { this(); } 

1 It doesn't have to be parameterless, strictly - if you add a Three(String... values) constructor, that's okay. You need to have a constructor that can be invoked with an empty argument list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM