EXAMPLE OF OVERRINDING STATIC METHOD IN JAVA

Chintoo Semi

Total Post:135

Points:947
Posted by  Chintoo Semi
Java  OOPS 
 1021  View(s)
Ratings:
Rate this:

i know that we cannot override static methods in java. I read here why:

but can someone explain the following code:

    class A

    {

        public static void a()

        {

            System.out.println("A.a()");

        }

    }  

 

    class B extends A

    {

        public static void a()

        {

            System.out.println("B.a()");

        }

    }

how was i able to override function a() in class B? why did it work here or am i missing something.

  1. Kamlakar Singh

    Post:194

    Points:1396
    Re: Example of Overrinding static method in java

    you didn't override anything here. To see for yourself, Try putting @Override annotation before public static void a() in class B and Java will throw an error.

    You just defined a function in class B called a(), which is distinct (no relation whatsoever) from the function a() in class A.

    But Because B.a() has the same name as a function in the parent class, it hides A.a() [As pointed by Eng. Fouad]. At runtime, the compiler uses the actual class of the declared reference to determine which method to run. For example,

    B b = new B();

           b.a();

           A a = (A)b;

           a.a()

    You cannot override static methods in Java. Remember static methods and fields are associated with the class, not with the objects. (Although, in some languages like Smalltalk, this is possible).

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!