--Originally published at tc2016blog
Since I didn’t make this post before, here it is.
I’ll be defining the four most basic concepts of Object-Oriented Programming (OOP) With a common acronym used by the OOP community APIE.
This acronym stands for Abstraction, Polymorphism, Inheritance and Encapsulation.
Inheritance is used to stop the code copy-pasting, by this I mean that if you have a class (e.g. Animal) which has certain attributes and methods you could use in another class (e.g. Dog), you should make the second class Dog inherit from the first class Animal, making them child and parent, or superclass and subclass, respectively. To do this we use the extends keyword after the subclass identifier and we write the superclass right besides it.
public class Dog extends Animal{
}
For example, I have an Animal class which has color and name attributes and a toWalk method, and want to create another class named Dog; instead of repeating the code to instantiate the color and name attributes and the toWalk method, I make it a subclass of Animal, so now Dog has all the attributes and methods Animal has by default.
Abstraction is similar to Inheritance, but in this case abstraction has a little bit more “power” if you’d like. By “power” I mean that an abstract class has the ability to choose which method any subclass HAS to use in order work correctly. In order to do this you should start by defining the class as an abstract class.
Encapsulation is to keep everything in one place, which is done with the different level modifiers public, private, protected and default. This is useful to avoid any variables being changed by any other actor aside from the class which instantiated them in the first place.
For example, in this WSQ I made:
As you can see I instantiated the int myNumber as private so only that class has modifying access to it and the GCD class can’t change it.
Polymorphism is the hardest one, the word, by etymology, means many forms, and in programming context it means that “classes have different functionality while sharing the same interface”.
Let me explain, this is closely related to Inheritance, this means that while a class can be used for many different functions, it can also be overridden for it to change its functionality and be more suitable for different applications. By overriding I mean literally overriding superclass’s methods in the subclass in order to return a different value or do a completely different thing, this is implemented in code with and override keyword while re-defining the method.
public class theExample extends PolyExample{
public override int randomMethod{
return 5;
}
}
Hope I helped, this was a long post, and hard one for Polymorphism, since I first had to really understand the concept in order to make the post more suitable for everyone.
References:
http://www.jakowicz.com/what-is-apie/
http://stackoverflow.com/questions/1031273/what-is-polymorphism-what-is-it-for-and-how-is-it-used