Question: [Check all the correct answers] Given the following calss definition: 1. public class DervedDemo extend Demo { 2. int M, N, L; 3. public DerivedDemo (int x, int y) { 4. M = x; N = y; 5. } 6. public DerivedDemo ( int x) { 7. super(x); 8. } 9. } Which of the follwing constructor signatures MUST exist in the Demo class for DerivedDemo to complie correctly? a public Demo(int a, int b) b public Demo(int a) c public Demo() The answer are b and c. Could you explain why c is necessary ?
Daniel
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
There is one concept in constructors and that is the objects should be constructed from top to bottom. So when you create a derived demo from the constructor ( int x , int y) it automatically puts a implicit call to super() . But here you have one more constructor that calls like super(x). now if the demo class has a constructor like demo( int x) then JAVA compiler does not provide the class with a default constructor . That is the explanation. Beaware , there will be many questions on this concept in exam
Carl Trusiak
Sheriff
Joined: Jun 13, 2000
Posts: 3340
posted
0
Originally posted by Daniel Liu: Question: [Check all the correct answers] Given the following calss definition: 1. public class DervedDemo extend Demo { 2. int M, N, L; 3. public DerivedDemo (int x, int y) { 4. M = x; N = y; 5. } 6. public DerivedDemo ( int x) { 7. super(x); 8. } 9. } Which of the follwing constructor signatures MUST exist in the Demo class for DerivedDemo to complie correctly? a public Demo(int a, int b) b public Demo(int a) c public Demo() The answer are b and c. Could you explain why c is necessary ?
Because unless you make a specific call to a constrictor in a super class, the default constrictor is called. In the constrictor public DerivedDemo (int x, int y) { M = x; N = y; } no called is made to super so, Demo() is called. Now since there is a call to super in the other constructor to super(int) you have to have a constrictor Demo(int) defined. When you define a constrictor, a default one isn't automatically generated and must be explicatly defined.