Get superclass value in Java

I have two 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?
    }
}

Solution

All methods in Java are virtual That is, there is no way to call the "super" version of a method from outside Converting to a won't help because it won't change the runtime type of the object

This may be your best choice / solution:

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
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>