2

Since a static method is restricted to a class only why is the subclass using the static method of the superclass in the below code?

public class StaticMethodEg extends Superclass {
    public static void main(String args[]) {
        System.out.println(StaticMethodEg.MyStaticMethod(2313123));
    }
}

class Superclass {
    public static int MyStaticMethod(int i) {
        Integer value = new Integer(i);
        return value + 1234;
    }
}

output

2314357
takendarkk
  • 3,347
  • 8
  • 25
  • 37

3 Answers3

1

Static methods are inheritable but not overridable.
So, the subclasses see the public static method of the parent class.

StaticMethodEg.MyStaticMethod(2313123) is legal but is is really misleading as it could give the impression that the StaticMethodEg class have a MyStaticMethod(int) that hides the static method of the parent. But it is not the case.

Superclass.MyStaticMethod(2313123) is clearer.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • Ohk means what i did is applicable but should not be valid...and also further proceeding i found that subclass which extends StaticMethodEg class also prints MyStaticMethod(2313123); method.Mean subclass of subclass also prints method of superclass. – shashi mishra Jun 01 '17 at 12:49
0

Your code is not compiling

 System.out.println(StaticMethodEg.MyStaticMethod(2313123));

you have to do

System.out.println(Superclass.MyStaticMethod(2313123));

Since static method is restricted to class only...

not really, the method is public so the StaticMethodEg class has access to that method too!

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

No, a public static method can be used anywhere, not only in the class it was declared in.

static methods are also inherited (like non-static methods), see this question for more information. In your case MyStaticMethod is inherited by StaticMethodEg class, as it extends Superclass .

syntagma
  • 23,346
  • 16
  • 78
  • 134