use java Home insert Page Layout References Malings Review View (3) (10 points/2
ID: 3755076 • Letter: U
Question
use java
Home insert Page Layout References Malings Review View (3) (10 points/2 points each) Calling super() and position of superl)question. Find the program chess.java in the same place as the last two questions. Loadit and run it. You should see this: Game constructor BoardGame constructor with i 99 Chess constructor // Add your answers as comments onto the code and submit it 1. What does the super(i) do in line 16? 2. Comment out super (i) in the BoardGame class, the compiler complains... Why? 3. Without uncommenting the (super (i)) back, how will you fix it (so the compiler would not the complaint )? What does super (99) in the chess class do? Put everything back the way it was (before step 1), now move super(i) ( line 16) to below the print (. line, the compiler complainsl! Why? 4. 5.Explanation / Answer
Q1) supper(i) - Calls the Base class Constructor ie Game and passes an int value i to initialize the Parent class Constructor
Q2) The compiler explains because in Base class Game we have defined an user defined Constructor to initialize i and when the Child class BoardGame inherits Game class, it must also obey the Parent class constructor call and without this, the compiler will report an error as child class tries to initailize value without initilaizing Parent class values.
Q3) Create a default no parametrized constructor for Game class. Code is shown below:-
class Game {
protected int i;
Game(){
}
Game(int i){
this.i = i;
System.out.println("Constructor is called");
}
}
class BoardGame extends Game{
BoardGame(int i) {
//super(i);
System.out.println("BoardGame constructor with i = " + i);
}
}
public class ChessGame {
// Rest code remains here
}
Q4) super(99) in Chess calls Parent Class Constructor Game and initializes i with value 99.
Q5) super should always be the first line while calling the Parent class constructor from Child Class.
Reason - The parent class' constructor needs to be called before the subclass' constructor. This will ensure that if you call any methods on the parent class in your constructor, the parent class has already been set up correctly.
In cases where a parent class has a default constructor the call to super is inserted for you automatically by the compiler. Since every class in Java inherits from Object, objects constructor must be called somehow and it must be executed first. The automatic insertion of super() by the compiler allows this. Enforcing super to appear first, enforces that constructor bodies are executed in the correct order which would be: Object -> Parent -> Child -> ChildOfChild -> SoOnSoForth.
Please let me know in case of any clarifications required. Thanks!
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.