1
class A{
   public int x;
    A(int x){
      this.x=x;
    }
}

class B extends A{
    public  int y;

    B(int x,int y){
        super(x);
        this.y=y;
    }

    int s=x+y;

    public void sum(){
        System.out.println("Sum is :"+s);
    }
}

public class Inheritance_2 {
     public static void main(String[] args) {
         B obj =new B(20,30);
         obj.sum();
     }
}

In this code, i wanna know why my sum is not 50 when I use s=x+y and print s?

But when I print (x+y) directly it gives the accurate result as 50.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
GeekDev
  • 9
  • 1
  • 3
    Your field int `s=x+y;` gets initialized before `this.y=y;` is executed. And it only gets initialized once at that specific time when `x` is `20` and `y` is still `0` – OH GOD SPIDERS May 12 '22 at 11:18

1 Answers1

0

you should add the sum inside the method :D

public void sum(){
    int s=x+y;
    System.out.println("Sum is :"+s);
}
Jon Ander
  • 740
  • 1
  • 14
  • 23