user3009344
user3009344

Reputation:

Use Overriden method

I am wondering, how in this example:

public class Test
{
    public int getA()
    {
        return 1;
    }
    public static class Test2 extends Test
    {
        @Override
        public int getA()
        {
            return 2;
        }
    }
    public static void main(String[] args)
    {
        Test2 a = new Test2();
        System.out.println(a.getA());
    }

Can i get 1 as result? Is there any way to do it? Getting Method of Test would be useful for me.

Upvotes: 0

Views: 48

Answers (2)

Ian Schmitz
Ian Schmitz

Reputation: 330

If you want to get 1 as a result you should be instantiating Test instead of Test2

Test a = new Test();
System.out.println(a.getA());

Upvotes: 1

Chris Zhang
Chris Zhang

Reputation: 968

Why would you want to get 1 when the getA() for Test2 returns 2 as per your specification? Seems counter-intuitive. No, there is no way because returning 2 instead of 1 is the point of overriding in the first place.

Upvotes: 1

Related Questions