4

When I execute:

 java B

for the following program, why does main of superclass A gets called? As I understand static methods belong to class level.

class A
{
    public static void main(String[] args)
    {
        System.out.println("A.main");
    }
}

class B extends A{ }
RRM
  • 2,495
  • 29
  • 46
  • 1
    Spoiler : yes they are – Aaron Jan 10 '17 at 11:02
  • 1
    @Aaron I don't think this is a duplicate, It also has to with the start up with JVM. – Tony Jan 10 '17 at 11:16
  • 1
    @Tony you're right there's a little more to it, but it can easily be made clear in a comment : `java B` will call `B.main(String[] args)`, which is the static `main(String[] args)` inherited from `A`. – Aaron Jan 10 '17 at 11:27
  • @Tony of course if you think there's more to it, feel free to vote to reopen the question, but I really think that the root of OP's misunderstanding was the false belief that static methods aren't inherited. – Aaron Jan 10 '17 at 11:29
  • @Aaron But it is different with call `B.main`. JVM invoke it using a more complicated way, how could OP be sure they have same effect? – Tony Jan 10 '17 at 11:30
  • @Tony What's that more complicated way you're talking about? Do you mean what happens in `java B` versus a `B.main()` called from Java code? It sure is different, but the contract of `java B` is to call the static `main(String[] args)` of `B`. I'm not sure I understand your concern. – Aaron Jan 10 '17 at 11:34

1 Answers1

1

Static methods are inherited by subclasses.

Adam Siemion
  • 15,569
  • 7
  • 58
  • 92