Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

this is the main class

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

this is the child class

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

how do i write the correct syntax? and the error is "constructor cannot be applied to given types"

like image 938
r4ccoon Avatar asked Jan 13 '10 11:01

r4ccoon


People also ask

Can we extend a class in main class in Java?

In Java, classes may extend only one superclass. Classes that do not specify a superclass with extends automatically inherit from java. lang. Object .

When parameters are added to the constructor in Java?

A parameterized constructor accepts parameters with which you can initialize the instance variables. Using parameterized constructor, you can initialize the class variables dynamically at the time of instantiating the class with distinct values.


2 Answers

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     }  } 
like image 138
Thomas Lötzer Avatar answered Oct 08 '22 10:10

Thomas Lötzer


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.

like image 42
Tadeusz Kopec for Ukraine Avatar answered Oct 08 '22 09:10

Tadeusz Kopec for Ukraine