Note that there are some explanatory texts on larger screens.

plurals
  1. POVariable Inheritance in Java
    primarykey
    data
    text
    <p>I have a Super class and a bunch of subclasses. I want to have one field that has the same name in every single subclass, but I do not want it to be defined in the super class, or at least I do not want to use that value. This is what I have right now</p> <pre><code>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(); } } </code></pre> <p>When I run Little, this is the output</p> <p>Big was here: told you, BIG</p> <p>I am not sure why 'told you' is printed out while tellMe refers to "BIG". How can both be true?</p> <p>My problem is that I want the method tellMe() to be in Big, and to have the variable tellMe (that it will actually return) to be defined in all the subclasses. The only way I can get this to work is as I have written, by rewriting the tellMe() method in each subclass. But doesn't that defeat the whole purpose of inheritance??? Please help</p> <p>EDIT: I do not use the constructor in my subclasses. All I want is a field that can be set in all subclasses and a method in the super that uses those values. I don't understand why this isn't possible because every subclass would have to implement it, so it would make sense... If this simply is not possible, let me know please</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload