Redefining static method in child class
Asked Answered
C

3

6

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

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 classe contain same methods ?

Q2 : If change the method in static to throw an exception not defined its not compiling. why is the case. Its obviously not overriding so i should be allowed to throw new exceptions right ?

public class Redefine extends Parent{
    public static void test () throws Exception{

    }
}
Civility answered 15/7, 2010 at 12:25 Comment(0)
J
10

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

A2: JLS 8.4.8 writes:

If a class declares a static method m, then the declaration m is said to hide any method m', where the signature of m is a subsignature (§8.4.2) of the signature of m', in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class.

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

Johathan answered 15/7, 2010 at 12:28 Comment(0)
E
4

you arent overriding it, you are hiding it

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

what exception are you getting?

Eckardt answered 15/7, 2010 at 12:31 Comment(0)
G
0

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 do you get?

Gadroon answered 15/7, 2010 at 12:32 Comment(1)
re: Q2: If you try the OP's version of Redefine.test() that is declared as throws Exception then you should get the compiler error Exception Exception is not compatible with throws clause in Parent.test().Roquefort

© 2022 - 2024 — McMap. All rights reserved.