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 - 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…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
-
(Locked)
What is inheritance?2m 41s
-
(Locked)
Leveraging different types of inheritance2m 49s
-
(Locked)
Using inheritance to reduce code duplication4m 51s
-
(Locked)
Discovering inheritance in foundational Java classes3m 18s
-
(Locked)
Challenge: Reduce redundant code with inheritance1m 51s
-
(Locked)
Solution: Reduce redundant code with inheritance4m 37s
-
(Locked)
-
-
-