I am now at the Abstraction part of the OOP.
To be honest, CodeCademy’s explanation and implementation is horrible and I just cannot understand anything for that concept.
I don’t understand what Abstraction is, why should I use it or what it is of use to me
I would be appreciative for an explanation because I am truly lost right now.
Abstraction is where you only deal with relevant details and hide the rest. It’s sort of the other side of Encapsulation.
So, whereas encapsulation is bundling stuff together and hiding it away. abstraction is allowing access to only the relevant data.
For example, say you have a car racing game and each different car was an instance of the Car class.
It could have a method that gets called when you press accelerate. All that method needs to know is ‘player presses accelerate, increase speed by this much’ and that would be the same no matter the type of car.
It doesn’t and shouldn’t need to know any other details about the car.
You can then apply the same method no matter the type of car (sports, truck, etc) and know it’ll respond in the same way for each - e.g. it wouldn’t suddenly break if you applied it to a car with 3 wheels, because that’s a detail it doesn’t know or care about.
Hope that’s helped a bit, but to be honest it took me a while to get it.
It may be useful to consider a functional type of abstraction. Consider,
def df(a=-9.81): ''' displacement due to acceleration as a function of time and initial velocity ''' def f(t,v=0): return v + a / 2 * t ** 2 # in the absence of friction with air return f >>> dg = df() >>> dg(10) -490.5 >>> dg(1) -4.905
A function factory is a function that returns a function with closure around the parameters of the parent function. Notice above we call
df() with no arguments. That is because it has a default parameter. We can overwrite it if we want a different acceleration in our return function. The default is acceleration due to gravity, which is a vector downwards, so has a negative value.
The returned function has that value tucked away as a constant so that we never need to provide it when we use that function. As well, our return function also presets initial velocity to zero, as though dropped from a height. Drop a ball from the roof of a bungalow and it will take about 1 second to hit the ground.
Our returned function only needs one input, time in seconds. We can include an initial velocity. This is perhaps a complicated example, but study it to get a grasp on how abstraction can be used in programming to simplify operations. The term is rather general, as there are multiple uses of abstraction, especially in D. R. Y. code.
Disclaimer: The above response by @pluginmaybe is completely notwithstanding. This is just a different example.