I have a Super class and a bunch of subclasses. I want to have one field with the same name in each subclass, but I do not want it to be defined in the superclass, or at least I do not want to use this value. This is what I have right now
public abstract class Big { public String tellMe = "BIG"; public Big() {} public void theMethod() { System.out.println ("Big was here: " + tellMe() + ", " + tellMe); } public String tellMe() { return tellMe; } } public class Little extends Big{ public String tellMe = "little"; public Little(){} public String tellMe() { return "told you"; } public static void main(String [] args) { Little l = new Little(); l.theMethod(); } }
When I launch Little, this is the conclusion
Big was here: told you BIG
I'm not sure why "told you" is printed, and tellMe is "BIG". How can both be true?
My problem is that I want the tellMe () method to be in Big, and that the tellMe variable (which it really returned) is defined in all subclasses. The only way to get this to work, as I wrote, is rewriting the tellMe () method in each subclass. But doesn't that defeat the whole purpose of inheritance ??? Please, help
EDIT: I do not use constructor in my subclasses. All I want is a field that can be set in all subclasses and in the super method that uses these values. I donโt understand why this is impossible, because each subclass would have to implement it, so it would make sense ... If this is simply impossible, please let us know.
source share