【问题标题】:java, extending class with the constructor of main class has parameterjava,用主类的构造函数扩展类有参数
【发布时间】:2010-01-13 11:03:21
【问题描述】:

嘿。语言是java。 我想扩展这个构造函数有参数的类。

这是主类

public class CAnimatedSprite {
     public CAnimatedSprite(String pFn, int pWidth, int pHeight) {
     }
}

这是子类

public class CMainCharacter extends CAnimatedSprite {

    //public void CMainCharacter:CAnimatedSprite(String pFn, int pWidth, int pHeight) {
    //}
}

如何编写正确的语法? 错误是“构造函数不能应用于给定类型”

【问题讨论】:

    标签: java


    【解决方案1】:

    你可以为你的构造函数定义任何你需要的参数,但是你必须调用超类的一个构造函数作为你自己构造函数的第一行。这可以使用super()super(arguments) 来完成。

    public class CMainCharacter extends CAnimatedSprite {
    
        public CMainCharacter() {
            super("your pFn value here", 0, 0);
            //do whatever you want to do in your constructor here
        }
    
        public CMainCharacter(String pFn, int pWidth, int pHeight) {
            super(pFn, pWidth, pHeight);
            //do whatever you want to do in your constructor here
        }
    
    }
    

    【讨论】:

    • 如果我的根类中有多个构造函数怎么办?我必须在我的扩展类中为它们中的每一个做 super() 吗?
    【解决方案2】:

    构造函数的第一条语句必须是对超类构造函数的调用。语法是:

    super(pFn, pWidth, pHeight);
    

    由您决定,是否希望您的类的构造函数具有相同的参数并将它们传递给超类构造函数:

    public CMainCharacter(String pFn, int pWidth, int pHeight) {
        super(pFn, pWidth, pHeight);
    }
    

    或传递其他内容,例如:

    public CMainCharacter() {
        super("", 7, 11);
    }
    

    并且不要为构造函数指定返回类型。这是违法的。

    【讨论】:

      【解决方案3】:
      public class CAnimatedSprite {
           public CAnimatedSprite(String pFn, int pWidth, int pHeight) {
           }
      }
      
      
      public class CMainCharacter extends CAnimatedSprite {
      
          // If you want your second constructor to have the same args
          public CMainCharacter(String pFn, int pWidth, int pHeight) {
              super(pFn, pWidth, pHeight);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-26
        • 2013-11-15
        • 1970-01-01
        • 1970-01-01
        • 2021-02-13
        • 2014-05-29
        • 2012-11-18
        • 1970-01-01
        相关资源
        最近更新 更多