开发者

How do I correctly Override in Java?

In my superclass, I have the following method:

public int getSpeed(String t)
{
    return 0;
}

In my subclass I them overide the method with this:

public int getSpeed(String t)
{
    return x;
}

I then have the following:

ArrayList<super> //contains only objects of the subclass
for (super s:collection)
{
    s.getSpeed("");
}

And this always returns 0. How do I get it to return x?


EDIT: My code was written almost exactly as Bala R's solution shows, however I just did something stupid to my X that caused it to round to 0 every time. His solution there开发者_StackOverflowfore is correct.


Maybe your x in the subclass is actually zero or not initialized ?

I just tried ( Ideone link )

import java.util.ArrayList;
public class Main {
    public static void main(String[] args) throws java.lang.Exception {

        new Main();
    }

    Main(){
        ArrayList<Super> list = new ArrayList<Super>();
        list.add(new Sub());
        list.add(new Sub());
        list.add(new Sub());
        for (Super s:list)
        {
            System.out.println(s.getSpeed(""));
        }
    }
}

class Super {
    public int getSpeed(String t) {
        return 0;
    }
}

class Sub extends Super {
    @Override
    public int getSpeed(String t) {
        return 1;
    }

}

and the output is

1
1
1


If the code is as you have written it in the question, then you've implemented overriding correctly. Alternative explanations for seeing zero speed values include:

  • The value of x has not been initialized, or has been set to zero.

  • The comment //contains only objects of the subclass is incorrect.

But I don't think we can say anything more without seeing the REAL code ...


Adding an @Override annotation to the overriding method is good way to ensure that you've overridden something ... and is good practice ... but it won't make any difference here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜