(Java Programming)
Question 8:
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
/*
3 is initialized as i when constructor is called for class ADD
for DAdd i is set to 1 for parent class and i for DAdd is set to 5
Addit method of ADD class is called and 3 is divided by i which is 2
and the output is 1
DA is copied to A and addit method is called
output: 2522
211 is passed to doubleit method of DAdd class
which further passed 422 to addit method
Output: 2950
*/
// Add class
class Add
{
protected int i;
Add(int a)
{
i = a;
}
protected void addIt(int amount)
{
i /= amount;
}
protected int getIt()
{
return i;
}
}
// DAdd class
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);
}
}
// TestAdder class
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());
}
}