class Parent { String s = "Parent"; public Parent(){ method(); } public void method(){ System.out.println(s); } } class Child extends Parent { String s = "Child"; public Child(){ } public void method(){ System.out.println(s); } } public class ObjectTest { public static void main(String[] args) { Child child = new Child(); } } output is : null I think it should be: Parent
When you invoke a method in the superclass constructor that is overridden in the subclass, then the overridden method is called. Since the subclass has not yet been initialized, s is null.
Hi, Null is being dislpayed because the print command is given in the class Child mathod() (offcourse overridden method will be called)which only recognizes the variable in class Child not Parent.Hence althought the value of variable s in Parent is "Parent" but the value of the variable s in Child will be printed.If you give in the Child method() a statemnt to print s you will get value Child.
when we create an instance for child... the child class constructor calls the super class contructor... wat will happen there... the variables in the superclass get declared or not... then wat happens wn it returns to sub class...