课程: Java Object-Oriented Programming

今天就学习课程吧!

今天就开通帐号,24,600 门业界名师课程任您挑!

Solution: Reduce redundant code with inheritance

Solution: Reduce redundant code with inheritance - Java教程

课程: Java Object-Oriented Programming

Solution: Reduce redundant code with inheritance

In addition to modding the size, we'll also want to make the index positive. To do that, we can use math.abs to make this index positive. Great, we have a valid index. Now we can just use the ArrayList functionality to retrieve the item. Since the get method is an instance method, we'll use the keyword this.get and pass in that validIndex. Whatever this returns is what we'll want to return from the function. Our implementation of getUsingMod is complete. Let's use it on our list in the Main function. We'll use it with a valid index, say one. We'll also try with a negative index, -2. And a large index, say 40. We'll also print these out to the console. The item at index one is 10. The item at a positive index 2 is 20. And since 40 is divisible by 4 with a remainder zero, it should retrieve the item at index zero. Let's run it. And we get the output we're expecting. Inheritance allowed us to use the ArrayList…

内容