*why won't this compile?*
Hi there,
Having a slight struggle trying to work out why this code won't compile, has anyone got any ideas?**
Code java:
public class ClassA
{
int x;
int y;
public ClassA(int theX, int theY)
{
x = theX;
y = theY;
}
}
public class ClassB extends ClassA
{
int z;
public ClassB(int x, int y, int z)
{
super(x, y);
this.z = z;
}
public ClassB(int z)
{
this.z = z;
}
}
Any help is appreciated!
tom
Re: *why won't this compile?*
Maybe have to call super in both constructors, have the one with just z for a param call super(0,0)
And also you probably need 2 files, incase thats in one file called ClassA, public class ClassB would need to be in a file names ClassB ...or something?
Re: *why won't this compile?*
What is/are the compiler error message(s)?
Re: *why won't this compile?*
I'm not getting any... Its the final question on a coursework - "following code for the two classes in the same package does not compile as expected. Why not?"
Then there are 6 answers (only 1 correct one) -
1.There is no zero-argument constructor in ClassB
2.There is no two-argument constructor in ClassA
3.There is no zero-argument constructor in ClassA
4.The three-argument constructor in ClassB should use this instead of super
5.There is no two-argument constructor in ClassB
6.There is no one-argument constructor ClassA
I'm completely rattled on this one, however I've got a feeling its 5? Does this make sense to anyone?!
cheers
tom
Re: *why won't this compile?*
Quote:
Originally Posted by
dcshoecousa
I'm not getting any...
Throw the code into the compiler and see what the error is/are. Then make an effort to fix said error. Once that is done, the solution should be obvious. If not, post back with details of what you did, how you did it, and why you are still confused.
Re: *why won't this compile?*
Throw out 1,2, and 4 right away.
I believe the answer is 3. That is based on the compiler error message I got in ClassB.
It's this part that's causing the problem:
Code java:
public ClassB(int z)
{
this.z = z;
}
implicit super constructor ClassA() is undefined. Must explicitly invoke another constructor.
However, why? I don't quite get why. I've never come across this type of error before. Do you always need a default, or 0 argument, constructor when you plan to extend that class?
When I add
public ClassA()
{
}
to ClassA the problem goes away, though what happens if I invoke an empty default constructor?
The answer is clearly choice 3.
Re: *why won't this compile?*
I guess the why is because the compiler must throw in a "super();" in any constructor that does not call super to initialize the superclass, makes sense indeed