Undefined constructor (java)

后端 未结 4 895
遇见更好的自我
遇见更好的自我 2021-01-21 23:16

so I have a java class called User that contains a constructor like this:

public class User extends Visitor {
    public User(String UName, String Ufname){
              


        
4条回答
  •  爱一瞬间的悲伤
    2021-01-21 23:37

    You need to know two things:

    1. At start of each constructor there is call to constructor of superclass. It is represented by

      • super() - invoke no-argument constructor of superclass
      • super(your,arguments) - invoke constructor handling arguments with same types as passed to super(..).

      If we want to use no-argument constructor we don't actually need to write super() because compiler will add code representing call to super() in binaries, but compiler can't do this nice thing for us if we want to call super with arguments because

      • it can't decide which constructor with arguments of superclass you want to use,
      • and what values (arguments) should be passed there,

      so in that case you need to explicitly write super(your,arguments) at start of your constructor yourself.

    2. If you will not add any constructor to your class compiler will add default constructor, which will have no arguments and its only instruction will be calling no-argument constructor of superclass super(). In other words code of classes like

      class Base{}
      class Derived extends Base{}
      

      is same as this code

      class Base extends Object{
          Base(){
              super();//will try to call Object() constructor
          }
      }
      class Derived extends Base{
          Derived(){
              super();//will try to call Base() constructor
          }
      }
      

    Now since in User class there is only one constructor User(String UName,String Ufname) when you try to compile

    public class Admin extends User {  
    
        public void manage_items() {            
            //...
        }
    
        public void manage_users() {   
            //...
        }
    }
    

    compiler see it as

    public class Admin extends User {  
    
        public Admin(){
            super();
        }
    
        public void manage_items() {            
            //...
        }
    
        public void manage_users() {   
            //...
        }
    }
    

    Now as you see problem lies in

        public Admin(){
            super();
        }
    

    because super() will try to invoke no-argument User() constructor, but there is no such constructor because only existing constructor in User class is User(String,String).

    So to make this work you need to add Admin constructor and at its start call super(someString, someString).

    So consider adding to your Admin class constructor like this one:

     public Admin(String aName,String Afname){
         super(aName, Afname);
         //here you can place rest of your constructors code
     }
    

提交回复
热议问题