I have a problem regarding this code that contains a Counter class, and MyCounter1 class, and a MyCounter2 class in Java;
I am wondering why the two outputs in the main method result in
output 1:
cnt1: 2 cnt2: 2
cnt1: 5 cnt2: 0
output 2:
cnt1: 3 cnt2: 3
cat1: 5 cnt2: 0
As far as I understood, when I call the constructor mycounter1 in the first line of code (Counter m = new myCounter 1();) int the main method, I call the constructor of the base class Counter first, which calls the method inc().
since inc() method is overwritten in myCounter1 class i will have to add 2 to cnt1 and cnt2. since my cnt1 is 5, why is the output for cnt1 still 2 and not 5+2=7? and where does the second result come from with cnt=5 and cnt=0 ?
class Counter {
int cnt1 = 5;
int cnt2;
void inc() {
cnt1 = cnt1 + 1;
cnt2 = cnt2 + 1;
}
public Counter() {
inc();
cnt1 = cnt2 = 0;
}
}
class MyCounter1 extends Counter {
int cnt1 = 5;
void inc() {
cnt1 = cnt1 + 2;
cnt2 = cnt2 + 2;
System.out.println("cnt1: " + cnt1 + " cnt2: " + cnt2);
}
public MyCounter1() {
System.out.println("cnt1: " + cnt1 + " cnt2: " + cnt2);
}
}
class MyCounter2 extends MyCounter1 {
int cnt1;
void inc() {
cnt1 = cnt1 + 3;
cnt2 = cnt2 + 3;
System.out.println("cnt1: " + cnt1 + " cnt2: " + cnt2);
}
}
public static void main(String[] b) {
Counter m = new MyCounter1(); ``
m = new MyCounter2();
}
inc) while in the constructor