Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java abstract class fields override

I have an abstract class that should implement a public field, this field is an interface or another abstract classe.

something like this:

public abstract class GenericContainer {
    public GenericChild child;
}

public abstract class GenericChild {
    public int prop1=1;
}

public abstract class SpecialChild extends GenericChild {
    public int prop1=2;
}

Now i have another specialized class Container:

public abstract class SpecialContainer extends GenericContainer {
    public SpecialChild child=new SpecialChild(); //PAY ATTENTION HERE!
}

Java allow me to compile this, and i IMAGINE that the field child in SpecialContainer is automatically overloading the field child of the GenericContainer... The questions are: Am i right on this? The automatic 'overloading' of child will happen?

And, more important question, if i have another class like this:

public class ExternalClass {
    public GenericContainer container=new SpecialContainer();
    public int test() {
         return container.child.prop1
    }
}

test() will return 1 or 2? i mean the GenericContainer container field what prop1 will call, the generic or the special? And what if the special prop1 was declared as String (yes java allow me to compile also in this case)?

Thanks!

like image 356
Alex Avatar asked Mar 09 '13 14:03

Alex


1 Answers

In Java, data members/attributes are not polymorphic. Overloading means that a field will have a different value depending from which class it's accessed. The field in the subclass will hide the field in the super-class, but both exists. The fields are invoked based on reference types, while methods are used of actual object. You can try it yourself.

It's called, variable hiding/shadowing, for more details look on here

like image 55
Abimaran Kugathasan Avatar answered Sep 28 '22 09:09

Abimaran Kugathasan