Question & Answer: Generate the output of the following program:…..

JAVA

Generate the output of the following program:

class Add {

protected int i;

Add(int a) {i = a;}

protected void addIt(int amount) {i /= amount;}

protected int getIt() {return i;}

}

class DAdd extends Add {

private int i;

DAdd(int a, int b) {

super(a);

i = b;

}

protected void addIt(int amount) {i = i * super.i + amount/ super.i ;}

protected int getIt() {return i + 1;}

protected void doubleIt(int amount) {addIt(2 * amount);}

}

public class TestAdder {

public static void main(String args[]) {

Add A = new Add(3);

DAdd DA = new DAdd(1, 5);

A.addIt(2);

System.out.println(A.getIt());

A = DA;

A.addIt(2522);

System.out.println(A.getIt());

DA.doubleIt(211;

System.out.println(A.getIt());

}

}

Expert Answer

 

Code with comments:

class Add {

protected int i;

Add(int a) {i = a;} //Add’s constructor

protected void addIt(int amount) {i /= amount;} //Add’s getIt method updating i to i/amount

protected int getIt() {return i;} //Add’s getIt method returning i

}

class DAdd extends Add { //class DAdd inheriting Add

private int i;

DAdd(int a, int b) { //DAdd’s constructor

super(a); //Calling Add’s constructor

i = b;

}

protected void addIt(int amount) {i = i * super.i + amount/ super.i ;} //DAdd’s addIt method which updates i to i*Add’s i + amount/add’s i

protected int getIt() {return i + 1;} //Dadd’s getIt method returning i+1

protected void doubleIt(int amount) {addIt(2 * amount);} //Dadd’s doubleIt method calling its add method by doubling the amount.

}

public class TestAdder {

public static void main(String args[]) {

Add A = new Add(3); //initializes Add’s i to 3

DAdd DA = new DAdd(1, 5); //initializes DAdd’s i to 5 and inherited Add’s i to 1

A.addIt(2); //dividing A.i by 2 and returning integer ie 3/2 = 1

System.out.println(A.getIt()); //printing A.i ie 1

A = DA; //asigning DA to A

A.addIt(2522); //calling DAdd’s addIt method : i = 5 * 1 + 2522/1 = 2527

System.out.println(A.getIt()); //calling DAdd’s getIt method to print i + 1 ie 2528

DA.doubleIt(211); //calling Dadd’s doubleIt method : this will call addIt(422) : 2527*1 + 422/1 = 2949

System.out.println(A.getIt()); //calling DAdd’s getIt method to print i + 1 ie 2950

}

}

Output :

Still stressed from student homework?
Get quality assistance from academic writers!