-4

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?

Robo Mop
  • 3,485
  • 1
  • 10
  • 23
  • 1
    It's not clear what the problem is. The variables will have a (non 0) value only when you initialize them. – Eran Jun 06 '17 at 07:37
  • I think the point that you're missing is that although a `Class3` object ***is a*** `Class2` object, an entirely different `Class2` object is created in the `call` method. So if the fields aren't `static`, you get a different copy of them in that created object than you have in the `Class3` object on which you call the method. – Dawood ibn Kareem Jun 06 '17 at 07:51
  • Possible duplicate of [Static variable in Java](https://stackoverflow.com/questions/12506082/static-variable-in-java) – Timothy Truckle Jun 06 '17 at 08:02

1 Answers1

0

static variables are those whose values will be constant for all objects of that class. Any change in them will be reflected in other objects too.

With non-static variables, object c will have its int a and int b i.e. c.a will be 3, and c.b will be 4. But these values belong to c; while super (another object for Class2) will have its values for a and b i.e. super.a and super.b as 0 and 0.

With static variables, when you create object c, you initialize a and b to 3 and 4, but now, every single object of Class2 (including super) will have a and b initialized to 3 and 4.

Robo Mop
  • 3,485
  • 1
  • 10
  • 23