0

If static members are not inheriting then why we can access it using sub class reference. Like in the given example we should not be able to access static method from class A by using Class A reference.

  package me.addicted.to.java;

    public class B extends A
    {

        public static void main(String[] args)
        {
            A.method();
            B.method();
            A a1 = new B();
            B test = new B();
            A arr[] = {a1,test};
            for(int i = 0; i < 2; i ++){
                arr[i].method();
            }
        }

    }
    class A
    {
        static int i = 10;
        static void method(){
            System.out.println("From Hello A");
    }
    }


Output : 

From Hello A

From Hello A

From Hello A

From Hello A
user207421
  • 305,947
  • 44
  • 307
  • 483
  • Because they belong to class `A` – Lrrr Jun 07 '15 at 18:12
  • 2
    You might look at my answer [here](http://stackoverflow.com/questions/29722682/static-method-behaving-like-other-method-those-can-override/29722779#29722779). It explains why this works. Your compiler/IDE should give you a warning about accessing a static member in a non-static fashion. – Turing85 Jun 07 '15 at 18:15
  • 1
    @yshavit Certainly it's a duplicate. The OP here is mistaken in thinking static members aren't inherited, and so evidently are you. You are both confusing inheritance with overriding. NB the duplicated question doesn't ask what you state. – user207421 Jun 07 '15 at 18:54

1 Answers1

1

well, static members are inherited, per JLS's jargon - http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.8

There's an exception - static methods in interfaces are not inherited.

ZhongYu
  • 19,446
  • 5
  • 33
  • 61