Question about Inherited member variables

Discussion in 'Java' started by marcwentink, Aug 24, 2006.

  1. marcwentink

    marcwentink Guest

    To my surprise this seems possible in Java:

    //-------------
    public class Base {
    protected int size = 100;
    public int getSize() {
    return size;
    }
    }

    public class SubClass extends Base {
    protected int size = 10;
    public int getSize(){
    return size;
    }
    public static void main(String[] args) {
    Base b = new SubClass();
    System.out.println (b.size + "," + b.getSize());
    }
    }
    //--------------

    Questions:

    1. Why does the declaration of size not lead to a compile error in
    SubClass, it seems to use a name already used.

    But I could accept that since in an inner loop you can also declare a
    variable with the same name as in the outer loop. I probably can
    compare it to that, right?

    2. Is the Base version of size still reachable in the Subclass by
    another statement? Something like Super()->size perhaps?

    Furthermore, I know this example should show me that overridden
    functions are subject of polymorphism, but vmember ariables are not.
    The outcome of the program is: 100, 10.
     
    marcwentink, Aug 24, 2006
    #1
    1. Advertisements

  2. IMHO this is bad design anyway. Rather make the member private and
    accessible via a getter only. If you want to prevent overriding you can
    make getter and setter final.
    It's in a different scope and depending on the compiler you use you
    might be able to get him give you a warning about a hidden member.
    Can you? I get an error for this

    for ( int i = 0; i < args.length; ++i ) {
    for ( int i = 0; i < args.length; ++i ) {
    System.out.println( i );
    }
    }
    public class SubClass extends Base {

    protected int size = 10;

    public int getSize() {
    return size;
    }

    public int getSuperSize() {
    return super.size;
    }

    public static void main( String[] args ) {
    SubClass b = new SubClass();
    System.out.println( b.size + "," + b.getSize() );
    System.out.println( b.getSuperSize() );
    }
    }
    What exactly do you want to say with this?
    Right.

    Kind regards

    robert
     
    Robert Klemme, Aug 24, 2006
    #2
    1. Advertisements

  3. marcwentink

    marcwentink Guest

    Robert Klemme schreef:
    Agreed, it is just an exercise example.
    I will try that. Perhaps this only goes for C++ then.

    Nothing much, just that my question is not about what the example
    program tried to explain, I got that.
    Hey thanks a lot!
     
    marcwentink, Aug 24, 2006
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.