0
public class StaticInnerClass {
 public static void main(String[] args) {


    //Outers out=new Outers();
    Outers.Inner1 in=new Outers.Inner2();
    in.display();
}
 }

class Outers
{
static class Inner1
{
    static void display()
    {
        display();
        System.out.println("Inner1");
    }
}

static class Inner2 extends Inner1
{
    static void display()
    {

        System.out.println("Inner2");
    }
}
}

The above program gives a stackoverflow error. Please explain that why doesn't it display "Inner1" because static methods don't override.

Neha Gupta
  • 847
  • 1
  • 8
  • 15

3 Answers3

7

The static method that executes is based on the static type, not the instance type:

Outers.Inner1 in=new Outers.Inner2();

So when you call this line, the static type is Outers.Inner1 and therefore it calls the display method that's part of this class, which calls itself repeatedly (causing the StackOverflowError.)

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
  • 1
    "Static type" means the type of the variable as seen by the compiler -- not the runtime type of the object, as it would be with non-static methods. – Ernest Friedman-Hill Sep 24 '13 at 11:34
1

Static methods are not invoked polymorphically!

This will cause the method display to invoke itself again and again until you get Stack Overflow Error. Also, see this question : Polymorphism and Static Methods

Community
  • 1
  • 1
Silviu Burcea
  • 5,103
  • 1
  • 29
  • 43
0
  1. A static method can't be overridden by sub class
  2. Static methods should be called with Class not with an object, even though you use object, it still going to use the type of the object.