问题
A little background:
There are three classes involved: Tester(main method)
, DNASequence(object)
and ProteinDNA(subclass of DNASequence)
. All three are under the same package.
The constructor for ProteinDNA
accepts an object DNASequence
and an integer
public class ProteinDNA extends DNASequence{
public ProteinDNA(DNASequence dna, int startAt){ //this is the constructor
Compiling the class ProteinDNA
gives me an error at the constructor.
The error in Eclipse is:
"Implicit super constructor `DNASequence()` is undefined.
Must explicitly invoke another constructor"
The error in jGrasp is:
ProteinDNA.java:16: error:
constructor DNASequence in class DNASequence cannot be applied to given types;
public ProteinDNA(DNASequence dna, int startAt)^{
required: String
found: no arguments
reason: actual and formal argument lists differ in length"
What am I doing wrong? The Tester class feeds the ProteinDNA
with an appropriately constructed instance of DNASequence
.
回答1:
Parent Class DNASequence has existing constructor with parameters. There 2 solutions for this.
1) You can add default no argument constructor to DNA Sequence class.
2) Modify child class constructor to invoke parent class constructor like below,
public ProteinDNA(DNASequence dna, int startAt){
super(....); // This should be the 1st line in constructor code, add parameters
as per parent constructor
}
回答2:
It looks like you are trying to pass a DNASequence object and that the thing that is failing is the building of that object.
required: String
found: no arguments
This makes me think that you probably try to do somthing like the following:
new ProteinDNA(new DNASequence(), num);
And the compiler says that it expects a String instead:
new ProteinDNA(new DNASequence("SOME STRING"), num);
Does that make sense?
Maybe we could be more helpful if you post some specific code, namely:
- ProteinDNA constructor invocation
- DNASequence constructors signatures
- Test method's code
Also, can you clarify why, if ProteinDNA is a subclass of DNASequence, you are passing a DNASequence to its constructor? Is that some kind of defensive copy?
Also, as mentioned in alternative answer, you might want to add the call to the super constructor (DNASequence(String)
) to the child constructor, as first line, like this:
super("SOME STRING")
But that really depends on your logic...
来源:https://stackoverflow.com/questions/19407061/java-extending-a-class-constructor-of-subclass-gives-error