3

I have 2 classes:

public class A
{    
    int n = 10;    

    public int getN()
    {
        return n;
    }    
}

public class B extends A
{    
    int n = 20;

    public int getN()
    {
        return n;
    }
}

public class Test
{    
    public static void main(String[] args)
    {           
        B b = new B();
        System.out.println(b.getN()); //--> return 20
        System.out.println(((A)b).getN()); //--> still return 20. 
                                           //How can I make it return 10?
    }
}
jball
  • 24,791
  • 9
  • 70
  • 92
Sean Nguyen
  • 12,528
  • 22
  • 74
  • 113

4 Answers4

5

All methods in Java are always virtual. That is, there is no way of invoking the "super"-version of the method from the outside. Casting to A won't help as it doesn't change the runtime type of the object.

This is probably your best alternative / workaround:

class A {

    int n = 10;

    public int getN() {
        return n;
    }

    public final int getSuperN() {  // "final" to make sure it's not overridden
        return n;
    }
}


class B extends A {

    int n = 20;

    public int getN() {
        return n;
    }
}

public class Main {

    public static void main(String[] args) {
        B b = new B();
        System.out.println(b.getN());      // --> return 20
        System.out.println(((A)b).getN()); // --> still return 20.
        System.out.println(b.getSuperN()); // --> prints 10
    }
}
aioobe
  • 413,195
  • 112
  • 811
  • 826
1

That thing won't work due to polymorphism. Class B is still class B even if you cast it into its super class.

I think you'll need something like this:

public class B extends A
{

   int n = 20;

   /**
   * @return the super n
   */
   public int getSuperN()
   {
      return super.n;
   }
}
Daniel Fath
  • 16,453
  • 7
  • 47
  • 82
1

you can't make the value be "10" because the instance of the object was for class B, and when you do the cast the only thing that are you doing is changing the define class not setting values for the object B, in other words if you need to get 10 its' something like this

b = new A();
Jorge
  • 17,896
  • 19
  • 80
  • 126
0

What you see is polymorphism in action. Since b is a B, that method (which returns 20) is always called (regardless if you cast it to an A).

Starkey
  • 9,673
  • 6
  • 31
  • 51