We can't override a static method by a non-static method why ??

Have a look at the below code...

class Parent
{
                   static void m1()
                           {
                                    System.out.println("static m1 in Test");
                            }
}

class Child extends Parent
{
                      void  m1()
                            {
                                      System.out.println("non static m1 in Test1");
                            }
}

class Demo
{
                  public static void main(String...args)
                            {
                                        Parent obj = new Child();
                                         obj.m1();          // Give Attention on This line

                            }
}

Now, picture is clear i think. Suppose compiler compiles this code without any problem then at compile time compiler checks the m1 method's availability and type in Parent class which is static Hence, changes obj to Parent (class name) .Its okay for now. Now you have your your byte code BUT at run time when JVM checks the object type it will call m1 method in the Child class but now the problem is obj (Refrence variable) have changed to class name Which is Parent (class name) and m1 method in the Child class is non-static then there will be a strange condition.
I think now it is clear that we can't override a static method by a non-static method & vice-versa .  

No comments:

Post a Comment