6

Is it possible to overload a field type to be another field type?

If so, would it be possible to provide some examples?

Brandon Wilson
  • 4,462
  • 7
  • 60
  • 90

4 Answers4

7

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.

Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 1
    I thought this was the case and I was bit confused at first when they came to me about it. I have only been programming Java for three years now and have not came across this. Just wanted to make sure I wasn't missing anything. – Brandon Wilson Jul 13 '12 at 16:14
  • 1
    @BrandonWilson it is not possible – Pooya Jul 13 '12 at 16:35
0

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

here's a tutorial

just make sure that you're not overloading public members that way.

0

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

Pooya
  • 4,385
  • 6
  • 45
  • 73
0

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); }
Community
  • 1
  • 1
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985