0
class A
{
        public static void func(int a)
        {
                System.out.println("In A : "+a);
        }
}

class B extends A
{
        public static void func(int a)
        {
                System.out.println("In B : "+a);
        }
}

public class StaticExample
{
        public static void main(String args[])
        {
                A a = new A();
                A aa = new B();
                B b = new B();

                a.func(1);
                aa.func(2);
                b.func(3);
        }
}

Why the output for the above code is

In A : 1
In A : 2
In B : 3

What I have read is that static methods cannot be overridden, then why such output is coming?

  • 1
    I don't see any evidence of overriding here. `aa.func(2)` says `In A`. – rgettman Jul 09 '18 at 17:44
  • Your problem belongs to the fact that static methods call from Class not from instance. As long as you defined `aa` as class A then `A.func()` called, and `b` is defined as class `B`, so `B.func() ` called. Maybe you need to follow IDE hints? usually they are there about static methods... BTW where did you read that "static methods cannot be overridden" ? – Vadim Jul 09 '18 at 18:10
  • it is true, static methods cannot be overridden. when you call `a.func()`, it is the same as calling `A.func()`. Same for `b.func()` which is `B.func`. What determine if `A` or `B` is used, is the type of the reference variable, which is known at compile time. In the case of `aa.func()`, the (compile) type of `aa` is `A` ; so `A.func()` gets called – Daniele Jul 09 '18 at 19:38

0 Answers0