Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overriding protected method of Superclass

In the below example why does the String b prints null and String c prints "gg".

Correct me if I am wrong, whenever a subclass (BClass) overrides a protected method (i.e initClass()) of the superclass (AClass).If you instantiate the subclass. The superclass must make use of overriden method specified by the subclass.

public class Example {

    public class AClass {

        private String a;

        public AClass() {
            initClass();
        }

        protected void initClass() {
            a = "randomtext";
        }
    }

    public class BClass extends AClass {

        private String b = null; 
        private String c;          


        @Override
        protected void initClass() {
            b = "omg!";
            c = "gg";
        }

        public void bValue() {
            System.out.println(b);   // prints null
            System.out.println(c);  // prints "gg"
        }
    }

    public static void main(String[] args) {
        Example.BClass b = new Example().new BClass();
        b.bValue();

    }

}
like image 249
Jaymit Desai Avatar asked Dec 12 '25 23:12

Jaymit Desai


2 Answers

As of the JSF 12.5

In the example you can see the execution order. The first steps are the callings of the Constructor down to the Object constructor. Afterwards this happens:

Next, all initializers for the instance variables of class [...] are executed.

Since your instance variable b is initialized to null it will be null again afterwards

like image 118
SomeJavaGuy Avatar answered Dec 15 '25 12:12

SomeJavaGuy


This is happening because the superclass constructor is called before the fields of ClassB is initialized. Hence the initClass() method is called which sets b = "omg!" but then again when the super class constructor returns, b is initialized to the value declared in ClassB which is null.

To debug, put a break point and go step by step, you will find that b is first set to null and then changes to omg! and then comes back to null.

like image 45
Codebender Avatar answered Dec 15 '25 13:12

Codebender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!