When I try to override a method that takes a List<String>, I get the following compile error.
Multiple markers at this line:
- The method getname(List<Integer>) of type child must override or implement a supertype method
- Name clash: The method getname(List<Integer>) of type child has the same erasure as getname(List<String>) of type parent but does not override it
I was under the impression, that due to erasure, a method that takes a List<String> and a subclass method that takes a List<Integer> would be considered as overridden, because the signature of both methods are same after erasure.
Here is the definition for method signature that involves erasure.
I do not understand why this error comes and what exactly it means.
My code is below:
class parent {
public void getname(List<String> num) {
System.out.printf("parent class: %s",num);
}
}
class child extends parent {
#Override // here is the compile error
public void getname(List<Integer> num) {
System.out.printf("child class: %s",num);
}
}
List<String> and List<Integer> are different types and getname(List<String> num) and getname(List<Integer> num) are methods with different signatures. So the second doesn't override the first. So child can not extends parent whit this method.
The error message is pretty clear: it has the same erasure, but the types don't match, so it's not considered an override. A List<Integer> is not a List<String>; it can't treat it as either an override (which would require the types to match exactly) nor an overload (which would require the erasures to be different).
Basically your impression is incorrect and this is impossible. The JLS considers this specifically illegal.
From 8.4.2:
The signature of a method m1 is a subsignature of the signature of a method m2 if either:
m2 has the same signature as m1, or
the signature of m1 is the same as the erasure (§4.6) of the signature of m2.
Two method signatures m1 and m2 are override-equivalent iff either m1 is a subsignature of m2 or m2 is a subsignature of m1.
The emboldened bit is important because it doesn't say "the erasure of m1 is the same as the erasure of m2". What it actually does allow is this (and some more convoluted examples like it):
class A {
void process(List<String> list) {}
}
class B extends A {
#Override
void process(List list) {} // |List| is erasure of List<T>
}
Since the method signature of B.process is the erasure of A.process it is an override.
According to 8.4.9, an example like in the OP could then be an overload because the signatures are not override-equivalent:
If two methods of a class ... have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.
Except that it's specifically a compile-time error (8.4.8.3):
It is a compile-time error if a type declaration T has a member method m1 and there exists a method m2 declared in T or a supertype of T such that all of the following conditions hold:
m1 and m2 have the same name.
m2 is accessible from T.
The signature of m1 is not a subsignature (§8.4.2) of the signature of m2.
The signature of m1 or some method m1 overrides (directly or indirectly) has the same erasure as the signature of m2 or some method m2 overrides (directly or indirectly).
These restrictions are necessary because generics are implemented via erasure. The rule above implies that methods declared in the same class with the same name must have different erasures. ...
To add to the answers already here, I want to comment about the signature of the methods is the same after erasure... but the compiler checks the method type before erasure.
You could do something like creating a "different" Parent class, such as
class Parent {
public void getname(List<Integer> num) {
System.out.printf("child class: %s",num);
}
}
, compile it, use it to compile Child class, and then mix your original Parent.class and Child.class in the same JVM without issue, avoiding the compiler checks and using type erasure.
But as long as the compiler notices doing something like that "in the same run", it will fail by the reasons explained by Ashot and Louis.
The error you have pointed out is obviously because of the #Override annotation. When validating annotations (which I presume must happen at the very early stage of compiling process) the type erasure hasn't occurred. So the types List is not same as List and you get the warning. But even without that annotation I get an error
name clash: getname(java.util.List<java.lang.Integer>) in child and getname(java.util.List<java.lang.String>) in parent have the same erasure, yet neither overrides the other
class child extends parent{`.
This error clearly says that they have the same erasure but still neither over rides. So Java in principle doesn't allow it.
I can understand it will lead to many problems/confusions if allowed. For e.g. if someone makes a call new Child().get_name( new List<String> () ), it can't be resolved to the Child method which will break the concept of over riding. So it is correct that it is not allowed.
Related
If three public interfaces are defined as:
public interface One{}
public interface Two{}
public interface Three{}
And another class, Super, is defined as:
public class Super {
public static <E extends One & Two & Three> void hmm(E item) {}
}
Why does the following subclass of Super give a compile error?
public class Subber extends Super{
public static void hmm(One item) {}
}
I would expect the above method to simply hide the method from Super, but that does not seem to be the case.
The JLS (8.4.8.2) says:
If a class C declares or inherits a static method m, then 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 C that would otherwise be accessible (§6.6) to code in C.
where a subsignature is defined in 8.4.2 as:
Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (§8.4.4), and, after adapting the formal parameter types of N to the the type parameters of M, the same formal parameter types.
The signature of a method m1 is a subsignature of the signature of a method m2 if either: m2 has the same signature as m1, or the signature of m1 is the same as the erasure (§4.6) of the signature of m2.
The erasure of a type variable is the erasure of its leftmost bound, as per JLS 4.6, so:
As far as I understand, Subber's hmm method is the same as the erasure of Super's hmm method, and would therefore be a subsignature of Super's hmm, thus meaning it would hide Super's hmm. However, the error message I get (from eclipse), which doesn't seem to make sense given the above is: "The method hmm(One) of type Subber has the same erasure as hmm(E) of type Super but does not hide it." What am I missing?
Edit: The precise error message, where the main method simply contains Subber.hmm(null); is:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Name clash: The method hmm(One) of type Subber has the same erasure as hmm(E) of type Super but does not hide it
at base/testpack4.Subber.hmm(Subber.java:4)
at base/testpack4.Main.main(Main.java:5)
Could someone explain why Subber's method does not compile, citing a credible source (preferably the JLS)?
„...Could someone explain why Subber's method does not compile...“
I implemented the code you listed; verbatim. And my Main.main(String[]) compiles fine with a call to Subber.hmm(null) and Subber.hmm(One).
The only thing different I did was introduce a new Four interface that meets the requirements of the type parameter section of <E extends One & Two & Three> void Super.hmm(E).
Then I passed an instance of Four into Subber.hmm(One) to confirm that Super.hmm(E) wasn't being called; proving it is actually hidden.
„...citing a credible source (preferably the JLS)?...“
That implementation behaves exactly as the JLS spec that you cited describes.
The type for E is still undefined, you can go and parameterize it via setting the E generic for the Super class and define it in the Subber class:
public class Super<E> {
public static <E extends One & Two & Three> void hmm(E item) {}
}
public class Subber extends Super<One> {
public static void hmm(One item) {}
}
I wonder why this is a valid override:
public abstract class A {
public abstract <X> Supplier<X> getSupplier();
public static class B extends A {
#Override
public Supplier<String> getSupplier() {
return String::new;
}
}
}
Whereas this is not:
public abstract class A {
public abstract <X> Supplier<X> getSuppliers(Collection<String> strings);
public static class B extends A {
#Override
public Supplier<String> getSuppliers(Collection<String> strings) {
return String::new;
}
}
}
According to JLS §8.4.8.1, B.getSupplier must be a subsignature A.getSupplier:
An instance method mC declared in or inherited by class C, overrides from C another method mA declared in class A, iff all of the following are true:
...
The signature of mC is a subsignature (§8.4.2) of the signature of mA.
...
Subsignatures are defined in JLS §8.4.2:
Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (§8.4.4), and, after adapting the formal parameter types of N to the the type parameters of M, the same formal parameter types.
The signature of a method m1 is a subsignature of the signature of a method m2 if either:
m2 has the same signature as m1, or
the signature of m1 is the same as the erasure (§4.6) of the signature of m2.
So it seems like B.getSupplier is a subsignature of A.getSupplier but B.getSuppliers is not a subsignature of A.getSuppliers.
I wonder how it can be the case.
If B.getSupplier is a subsignature of A.getSupplier because it has the same erasure, then B.getSuppliers must also have the same erasure as A.getSuppliers. This should suffice for overriding getSuppliers to be legal - but it does not.
If B.getSupplier is a subsignature of A.getSupplier because it has the same signature, then I wonder what "the same type parameters (if any)" exactly means.
If type parameters are considered, then they should have different type parameters: A.getSupplier has type parameter X, B.getSupplier has none.
If type parameters are not considered then how's getSuppliers different?
This is more of an academic question about overrides and generics so please don't suggest refactoring code (like moving type parameter X to the class etc.).
I am looking for a formal, JLS-based answer.
From my point of view B.getSupplier should not be able override A.getSupplier as they don't have the same type parameters. This makes the following code (which produces ClassCastException) legal:
A b = new B();
URL url = b.<URL>getSupplier().get();
According to the compiler output, the method signatures are different in both examples (compile the code with -Xlint:unchecked option to confirm it):
<X>getSupplier() in A (m2)
1st snippet
getSupplier() in B (m1)
<X>getSuppliers(Collection<String> strings) in A (m2)
2nd snippet
getSuppliers(Collection<String> strings) in B (m1)
According to the JLS specification, the signature of a method m1 is a subsignature of the signature of a method m2 if either:
m2 has the same signature as m1, or
the signature of m1 is the same as the erasure of the signature of m2.
The first statement is out of the game - method signatures are different. But what about the second statement and erasure?
Valid Override
B.getSupplier() (m1) is a subsignature of A.<X>getSupplier() (m2), because:
the signature of m1 is the same as the erasure of the signature of m2
<X>getSupplier() after erasure is equal to getSupplier().
Invalid Override
B.getSuppliers(...) (m1) is not a subsignature of A.<X>getSuppliers(...) (m2), because:
the signature of m1 is not the same as the erasure of the signature of m2
The signature of m1:
getSuppliers(Collection<String> strings);
Erasure of the signature of m2:
getSuppliers(Collection strings);
Changing m1 argument from Collection<String> to the raw Collection eliminates an error, in this case m1 becomes a subsignature of m2.
Conclusion
1st code snippet (valid override): the method signatures in the parent and child classes are different initially. But, after applying the erasure to the parent method the signatures becomes the same.
2nd code snippet (invalid override): the method signatures are different initially and remains different after applying the erasure to the parent method.
The moment you added the parameter it ceased to be an override and became an overload.
Generics have nothing to do with it.
I wonder why this is a valid override:
public abstract class A {
public abstract <X> Supplier<X> getSupplier();
public static class B extends A {
#Override
public Supplier<String> getSupplier() {
return String::new;
}
}
}
Whereas this is not:
public abstract class A {
public abstract <X> Supplier<X> getSuppliers(Collection<String> strings);
public static class B extends A {
#Override
public Supplier<String> getSuppliers(Collection<String> strings) {
return String::new;
}
}
}
According to JLS §8.4.8.1, B.getSupplier must be a subsignature A.getSupplier:
An instance method mC declared in or inherited by class C, overrides from C another method mA declared in class A, iff all of the following are true:
...
The signature of mC is a subsignature (§8.4.2) of the signature of mA.
...
Subsignatures are defined in JLS §8.4.2:
Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (§8.4.4), and, after adapting the formal parameter types of N to the the type parameters of M, the same formal parameter types.
The signature of a method m1 is a subsignature of the signature of a method m2 if either:
m2 has the same signature as m1, or
the signature of m1 is the same as the erasure (§4.6) of the signature of m2.
So it seems like B.getSupplier is a subsignature of A.getSupplier but B.getSuppliers is not a subsignature of A.getSuppliers.
I wonder how it can be the case.
If B.getSupplier is a subsignature of A.getSupplier because it has the same erasure, then B.getSuppliers must also have the same erasure as A.getSuppliers. This should suffice for overriding getSuppliers to be legal - but it does not.
If B.getSupplier is a subsignature of A.getSupplier because it has the same signature, then I wonder what "the same type parameters (if any)" exactly means.
If type parameters are considered, then they should have different type parameters: A.getSupplier has type parameter X, B.getSupplier has none.
If type parameters are not considered then how's getSuppliers different?
This is more of an academic question about overrides and generics so please don't suggest refactoring code (like moving type parameter X to the class etc.).
I am looking for a formal, JLS-based answer.
From my point of view B.getSupplier should not be able override A.getSupplier as they don't have the same type parameters. This makes the following code (which produces ClassCastException) legal:
A b = new B();
URL url = b.<URL>getSupplier().get();
According to the compiler output, the method signatures are different in both examples (compile the code with -Xlint:unchecked option to confirm it):
<X>getSupplier() in A (m2)
1st snippet
getSupplier() in B (m1)
<X>getSuppliers(Collection<String> strings) in A (m2)
2nd snippet
getSuppliers(Collection<String> strings) in B (m1)
According to the JLS specification, the signature of a method m1 is a subsignature of the signature of a method m2 if either:
m2 has the same signature as m1, or
the signature of m1 is the same as the erasure of the signature of m2.
The first statement is out of the game - method signatures are different. But what about the second statement and erasure?
Valid Override
B.getSupplier() (m1) is a subsignature of A.<X>getSupplier() (m2), because:
the signature of m1 is the same as the erasure of the signature of m2
<X>getSupplier() after erasure is equal to getSupplier().
Invalid Override
B.getSuppliers(...) (m1) is not a subsignature of A.<X>getSuppliers(...) (m2), because:
the signature of m1 is not the same as the erasure of the signature of m2
The signature of m1:
getSuppliers(Collection<String> strings);
Erasure of the signature of m2:
getSuppliers(Collection strings);
Changing m1 argument from Collection<String> to the raw Collection eliminates an error, in this case m1 becomes a subsignature of m2.
Conclusion
1st code snippet (valid override): the method signatures in the parent and child classes are different initially. But, after applying the erasure to the parent method the signatures becomes the same.
2nd code snippet (invalid override): the method signatures are different initially and remains different after applying the erasure to the parent method.
The moment you added the parameter it ceased to be an override and became an overload.
Generics have nothing to do with it.
I came across an example that suggests that erasure is done differently on the method signature and method, but I don't know why/how. The JLS §8.4.8.3 states:
It is a compile-time error if a type declaration T has a member method m1 and there exists a method m2 declared in T or a supertype of T such that all of the following conditions hold:
m1 and m2 have the same name.
m2 is accessible from T.
The signature of m1 is not a subsignature (§8.4.2) of the signature of m2.
The signature of m1 or some method m1 overrides (directly or indirectly) has the same erasure as the signature of m2 or some method m2 overrides (directly or indirectly).
The compile-time error example given:
class C<T> {
T id (T x) {...}
}
class D extends C<String> {
Object id(Object x) {...}
}
The explanation:
This is illegal since D.id(Object) is a member of D, C.id(String) is declared in a supertype of D, and:
The two methods have the same name, id
C.id(String) is accessible to D
The signature of D.id(Object) is not a subsignature of that of C.id(String)
The two methods have the same erasure
The first two points are obvious, but I don't understand the last two points of the explanation. How can the two methods have the same erasure if the third point holds? From the third point, it seems the erasure of signature is done using the parameterized class C<String>'s method (i.e. id(String) instead of id(T)). If that is the case, then the two methods should have different erasures, but the example suggests that method erasure is done on the non-parameterized class. So, how is erasure actually applied on the method signature and method?
Erasure means that all occurences of generic type T (String in case of C) are replaced by Object (+ required type casts). As type informations are lost this way, there is a conflict in the example - the JVM would not be able to decide which method to call.
edit(this is wrong):
afaik : A subsignature would be a method that accepts a compatible type (e.g. a super type of String) and/or returns a covariant type.
I tried it out and it is confusing, but came to this explanation: The compiler does not erase, but replace generic signatures. Therefore, when D extends C<String> the signature of the overriden C<String>.id becomes: String id(String x). Clearly D's method id has not the same signature and also not the same erasure (because String is not a generic type). Therefore the signature of D.id is not a subsignature of C. (That matches rule 3)
On the other hand, the erasure of C<T>.id(T x) is Object id(Object x) and identical to the erasure of D.id(Object x). (That matches rule 4)
Following that, it would be valid to override id if one could keep the signatures and erasures aligned. And apparently that is possible (although not really useful):
class Foo<T> {
public void set(final T thing) {}
}
class Bar<T> extends Foo<T> {
#Override
public void set(final Object thing) {}
}
This compiles in eclipse without warning.
So, I was trying to write a method to answer one of my previous questions: How can I find out if an arbitrary java.lang.Method overrides another one? To do that, I was reading through the JLS, and there are some parts that seem to be missing in one case.
Imagine you have the following classes:
public class A<T> {
public void foo(T param){};
}
public class B extends A<String> {
public void foo(String param){};
}
In this case, it is quite obvious that B.foo overrides A.foo, however I don't understand how this case fits the specification.
Regarding method overriding, the JLS §8.4.8.1 states:
An instance method m1, declared in class C, overrides another instance method m2, declared in class A iff all of the following are true:
C is a subclass of A.
The signature of m1 is a subsignature (§8.4.2) of the signature of m2.
Either:
m2 is public, protected, or declared with default access in the same package as C,or
m1 overrides a method m3 (m3 distinct from m1, m3 distinct from m2), such that m3 overrides m2.
Obviously points 1 and 3 are satisfied in our case. Let's look a bit deeper in the JLS what subsignature means. The JLS §8.4.2 says:
Two methods have the same signature if they have the same name and argument types.
Two method or constructor declarations M and N have the same argument types if all of the following conditions hold:
They have the same number of formal parameters (possibly zero)
They have the same number of type parameters (possibly zero)
Let A1, ..., An be the type parameters of M and let B1, ..., Bn be the type parameters of N. After renaming each occurrence of a Bi in N's type to Ai, the bounds of corresponding type variables are the same, and the formal parameter types of M and N are the same.
In our case, point 1 is clearly true (both have 1 argument).
Point 2 is a bit more muddy (and that's where I'm not sure what the spec means exactly): Neither of the methods declare their own type parameters, but A.foo uses T which is a type variable that paramterizes the class.
So my first question is: in this context, do Type variables declared in the class count or not?
Ok, now let's assume that T doesn't count and that therefore point 2 is false (I don't know how I could even apply point 3 in this case). Our two methods do not have the same signature, but that doesn't prevent B.foo from being a subsignature of A.foo.
A little further in JLS §8.4.2 it says:
The signature of a method m1 is a subsignature of the signature of a method m2 if either:
m2 has the same signature as m1, or
the signature of m1 is the same as the erasure (§4.6) of the signature of m2.
We have already determined that point 1 is false.
The erasure signature of a method according to JLS §4.6 is a signature consisting of the same name as s and the erasures of all the formal parameter types given in s. So the erasure of A.foo is foo(Object) and the erasure of B.foo is foo(String). These two are different signatures, therefore point 2 is also false, and B.foo is not a subsignature of A.foo, and therefore B.foo does not override A.foo.
Except it does...
What am I missing? Is there some piece of the puzzle that I'm not seeing, or is the spec really not complete in this case?
do Type variables declared in the class count or not?
The elements in question are the methods, not the containing type declarations. So, no, they don't count.
Ok, now let's assume that T doesn't count and that therefore point 2 is false
Why? They both have 0 type parameters, so it's true.
Step by step:
They have the same number of formal parameters (possibly zero)
Both methods have 1 formal parameter. Check.
They have the same number of type parameters (possibly zero)
Neither method declares a type parameter. Check.
Let A1, ..., An be the type parameters of M and let B1, ..., Bn be the type parameters of N. After renaming each occurrence of a Bi in N's type to Ai, the bounds of corresponding type variables are the same, and the formal parameter types of M and N are the same.
Since neither method declares a type parameter there's nothing to rename and the formal parameter types are the same -- T[T=String] = String. Check.
⇒ B.foo(String) has the same signature as A<String>.foo(String).
⇒ B.foo(String) is a subsignature of A<String>.foo(String)
Since B is a subclass of A and A<String>.foo(String) is public we can conclude B.foo(String) overrides A<String>.foo(String).
You must look at it this way:
The class B extends the type A<String>, which has a method foo(String param).
A<String> is an invocation of the generic type A<T>. It is a type in its own right. This is implied by JLS 4.5, which defines what a parameterized type is. A<String> is a parameterized type and is on equal footing with any other reference type. The fact that it is parameterized is not important when discussing the concept of the direct superclass.
Excerpt from Oracle's tutorial on generics:
After type erasure, the method signatures do not not match. The Node method becomes setData(Object) and the MyNode method becomes setData(Integer). Therefore, the MyNode setData method does not override the Node setData method.
To solve this problem and preserve the polymorphism of generic types after type erasure, a Java compiler generates a bridge method to ensure that subtyping works as expected.
So basically, compiler magic makes your compiled code work as expected, even with the JLS as it is. I'm not sure where this behavior is specified.