Overriding a static method in a child class

I would like to know the reason why this is first allowed in Java (or, in general, oops) I remember that static methods are common to the parent and child classes

public class Redefine extends Parent{ public static void test () { } } class Parent{ public static void test () { } } 

Q1: Since Overriding is not supported for static methods, how can both classes contain the same methods?

Q2: If you change the method to static to throw an exception, do not compile it. why is that. Obviously this does not override, so should I be allowed to throw new exceptions correctly?

 public class Redefine extends Parent{ public static void test () throws Exception{ } } 
+6
java inheritance static scjp
source share
3 answers

Method A1:: static refers to the class. They have nothing to do with inheritance hierarchies in terms of polymorphism. So calling Parent.test() will call the parent method, and calling Redefine.test() will call the child.

A2: JLS 8.4.8 writes:

If the class declares a static method m, then it is said that the declaration m hides some method m ', where the signature m is the submission (ยง8.4.2) of the signature m', in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the classroom.

A method declaration should not have a throws clause that conflicts (ยง8.4.6) with a declaration of any method that it overrides or hides; otherwise, a compile-time error occurs.

+10
source share

you arent redefining it, you hide it

http://faq.javaranch.com/java/OverridingVsHiding

what exception do you get?

+4
source share

Q1: Static methods are not overridden, so these are two different methods with the same signature. One is called with Parent.test (), the other is called with Redefine.test ()

Q2: Your method seems valid. What error are you getting?

0
source share

All Articles