Get superclass value in java

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?
    }
}
+3
source share
4 answers

All methods in Java are always virtual. That is, there is no way to call a "super" version of the method from the outside. Execution Adoes not help, because it does not change the type of runtime 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 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
    }
}
+5
source

This thing will not work due to polymorphism. A class Bis still a class B, even if you included it in your superclass.

I think you will need something like this:

public class B extends A
{

   int n = 20;

   /**
   * @return the super n
   */
   public int getSuperN()
   {
      return super.n;
   }
}
+1
source

you cannot make the value “10” because the instance of the object was for class B, and when you throw, the only thing you do is change the define class that does not set the value for object B, in other words, if you need to get 10 his "something like this

b = new A();
+1
source

What you see is polymorphism in action. Since it bis b, this method (which returns 20) is always called (regardless of whether you drop it in A).

0
source

Source: https://habr.com/ru/post/1772556/


All Articles