Home > Software design >  Any one Explain the output below java programme?
Any one Explain the output below java programme?

Time:09-17

Why does folowing program produce output 0 according to my knowledge output has to be 100

  class A{
           int value=100;
    public void printValue(){
    System.out.println("Value from A : " value);
    }
    A(){
        printValue();
     }
    }
    class B extends A{
    int value=200;
     public void printValue(){
        System.out.println("Value from B : " value);
     }
    }
    class Demo{ 
        public static void main(String args[]){  
        new B();
     }   
    }

The output is followings: Value from B : 0

CodePudding user response:

First you need to understand somethings like class B is inheriting Class A and both the classes are having a common method printValue, At this the concept of method overriding comes in frame. "Method Overriding happens between classes" so we have simply "Overridden" the printValue present in the "class A" by using it in "class B".

"Both methods are having the Same the "name", "return type" and "argument list" because the concept of method Overriding follows this."

Second thing when you have created the object of "class B" its default constructor will be called, But before that "Class A" constructor will be called because it is the super class of "class B".

Now the constructor present in the "class A" is calling the "printValue", But it will not call the method present in "class A", it will call the method of "class B", And this all steps happens before the 200 got initialized in "value" variable of "class B".

So that's why it is printing Value from B : 0


Value from A : 100

will get printed when the method present in "class A" will be static, In that case we will simply call method printValue by using the name of class. for that we have to make the printValue a "static" method., And the "value" variable will also changed to "static" because "A static method can't access non-static variables"

After this the Value from A : 100 will get printed.

But as you are making the "printValue" method static, which is a "Overridden method" and present in "class B" also than you will have to make method present in "class B" "static" and "variable" also will be "static".``

CodePudding user response:

When you call the new B(); it is going to all the constructor of parent class i.e. A(). Then the constructor calls the printValue() method of B. Till here we haven't initialized the value. As the default value of int is zero. Hence the same will be printed.

CodePudding user response:

When you instantiating class B with new B() by default it call its parent constructor A()

Where inside constructor again call the method printValue() which is already override by child class A

Since at the time of printValue() involking in class B the value property has not initialized so it took the default value of int 0; will print Value from B : 0

  • Related