Is it possible to overload a field type to be another field type?
If so, would it be possible to provide some examples?
Is it possible to overload a field type to be another field type?
If so, would it be possible to provide some examples?
You can't overload fields (only methods can be overloaded), you might be confused with overriding fields - which anyway is not possible, you end up hiding the fields from superclasses. Take a look at this post.
I believe that java supports interfaces, and interfaces should be able to help you achieve what you're trying to achieve
here's an example i found quick
just make sure that you're not overloading public members that way.
look at this code
class A<T> {
protected T field1;
}
class B extends A<String> {
public char field1;
public static void main(String[] args) {
A a = new B();
a.field1 = 12442;
}
}
it runs without any exception, if field1 overrided, it should raise an exception, but it doesn't
and also this runs without any exception
class A<T> {
protected T field1;
}
class B extends A<Character> {
public char field1;
public static void main(String[] args) {
A a = new B();
a.field1 = 12442;
}
}
It's impossible
The Java language (JLS) does not allow it, but Java bytecode (JVMS) does
Oracle JDK 1.8.0_45 even relies on it to implement assert
. For example:
public class Assert {
static final int[] $assertionsDisabled = new int[0];
public static void main(String[] args) {
System.out.println(int.length);
assert System.currentTimeMillis() == 0L;
}
}
generates two Oracle JDK 1.8.0_45
, one explicit (int[]
) and one synthetic (bool
), and is happily able to distinguish between them. But if we had declared:
static final boolean $assertionsDisabled = false;
it would fail to compile with:
the symbol $assertionsDisabled conflicts with a compile synthesized symbo
See https://stackoverflow.com/a/31355548/895245 for more details.
Possible rationale why it's not possible
The problem is that it would not be possible to determine the type of the field. Consider:
void f(int i) { System.out.println("int"); }
void f(float i) { System.out.println("float"); }
int i;
float i;
// Which overridden method is called?
void m() { f(i); }