what output is produced by the following code and explain how it works.
public class A {
int a = 1;
int b = 2;
public int getSum(int a, int b) {
this.a+=a;
this.b+=b;
return this.a + this.b;
}
}
public class B extends A {
int a = 3;
int b = 4;
public int getSum(int a, int b) {
this.b=a;
super.b=b+b;
return super.a+this.b;
}
}
public class q2 {
public static void main(String[] args){
A a = new A();
B b = new B();
System.out.println(a.a + " " + b.b);
System.out.println(a.getSum(a.a, b.b));
System.out.println(a.b + " " + b.b);
System.out.println(b.getSum(a.b, b.b));
System.out.println(a.a+" "+a.b + " " +b.a+" "+b.b);
}
}
Output:
1 4
8
6 4
7
2 6 3 6
Here we have created 2 objects
a.a=1
a.b=2
b.a=3
b.b=4
we are printing a.a and b.b so it will be 1 4
next we are calling sum with 1,4
so it will 1 a.a so it will be 2 and 4 to a.b so it will be 6
so it will return 8
printing a.b and b.b so 6 4
again getSum will return 7
final values will be 2 6 3 6
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me
Get Answers For Free
Most questions answered within 1 hours.