Let's talk about basic object orientation in java.
If you're used to programming java, you've definitely seen something like this:
And off you go programming away. Suddenly you want to describe a fraction. Your annoying younger sibling just covered them in elementary school and he's asking you what they look like. You agree to print use your magical programming abilities to show him how they work.
But after you show him the first fraction, he wants to see another one. You have no choice but to go back and start copying your fraction code, renaming the variables of course.
If this pattern continues, you're going to spend way too much time typing the same fraction code over and over and over again. Eventually your program will turn into a giant fraction. And what if your little brother wants you to divide or multiple two specific fractions? If you have ten or fifteen of them, how are you going to remember which set of fraction variables represent what?
Object orientation to the rescue! In this context, object orientation is the ability to describe the IDEA of a thing in code before you actually create it. Up until now we've been describing specific fractions (1/2 and 3/5). But what if we could describe the concept of a fraction?
So now we've described the idea of a fraction. It has a numerator, a denominator, and a method that knows how to print out the fraction. We haven't created any specific fraction yet, we've just created something that describes a fraction. Let's go back and simplify our code for our little brother.
It's been cut down to two lines per fraction. And if we want to add more fractions in the future, it's simple!
We can also add more functionality to our Fraction class. What if we wanted to add a divide method to our fraction class to show our little bro? Simple!
I set it up this way so we can read it fraction1 dividedBy fraction2. In code it would look like
Pretty slick huh? Getting the programming bug yet?







No comments:
Post a Comment