From the course: Java Object-Oriented Programming

Unlock the full course today

Join today to access over 23,200 courses taught by industry experts.

Solution: Reduce redundant code with inheritance

Solution: Reduce redundant code with inheritance - Java Tutorial

From the course: 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…

Contents