java, extending class with the constructor of main class has parameter

后端 未结 3 1050
粉色の甜心
粉色の甜心 2020-11-29 07:23

hei. the language is java. i want to extend this class which the constructor has parameters.

this is the main class

public class CAnimatedSprite {
           


        
相关标签:
3条回答
  • 2020-11-29 08:06

    You can define any arguments you need for your constructor, but it is necessary to call one constructor of the super class as the first line of your own constructor. This can be done using super() or 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
        }
    
    }
    
    0 讨论(0)
  • 2020-11-29 08:09

    The first statement of your constructor must be a call to superclass constructor. The syntax is:

    super(pFn, pWidth, pHeight);
    

    It is up to you to decide, whether you want constructor of your class to have same parameters and just pass them to superclass constructor:

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

    or pass something else, like:

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

    And don't specify return type for constructors. It's illegal.

    0 讨论(0)
  • 2020-11-29 08:09
    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题