I have two classes. Class2 and Class3. Class2 is parent class of child Class3.
package package1;
public class Class2 {
public static int a, b;
public void add() {
System.out.println("the sum is =" + (a + b));
}
public void product() {
System.out.println("the product is " + (a * b));
}
public Class2() {
System.out.println("class 2 constructor");
}
public Class2(int a, int b) {
this.a = a;
this.b = b;
}
}
And the code for Class3 is
package package2;
import package1.*;
public class Class3 extends Class2 {
public Class3(){
//super(3,4);
call();
System.out.println(super.a);
System.out.println(b);
System.out.println("class 3 constructor");
}
public void call(){
Class2 c=new Class2(3,4);
super.add();
super.product();
}
public void add(){
System.out.println("child class add method");
}
}
The above code works fine and the output is
class 2 constructor
the sum is =7
the product is 12
3
4
class 3 constructor
Problem: when i make the parent class variables non-static, then the value is not initialized the the result look like this
class 2 constructor ,
the sum is =0
the product is 0
0
0
class 3 constructor.
But while keeping variables non-static if i call the parent class constructor in child class using super(), then it gives the result. what is the reason of this problem and how can i solve it?