How to - Java Interfaces and Abstrac Classes

Today's topic - what is an interface? And what the hell does that have to do with abstract classes?

As you can see, we introduce this program not as a class, but an interface. Inside the interface there are methods, which can or can not contain any kind of parameters but the bodies of these methods are empty. 
But why would you want that .__.

Look at the interface as a kind of blueprint. When you are a contractor and you are supposed to build a whole neighbourhood with 14 houses that look the same (kitchen, 2 bedrooms, 3 baths and a porch) you might not want to sit down at your desk 14 times and draw plans for every single house if they are going to look the same fucking way in the end ._.

Sure, you might want to paint one green and the other red - but that can be added later on.

So our interface is a blueprint for a type of class that should in the future be used over and over again, with the same kinds of methods in them.
Note here: once you implement an interface int a class like such:

You must implement every method from the interface in equal measure as you did inside the original interface!

___________________________________________________________

Now we come to abstract classes. An abstract class has a similar use like an interface, but this is a class, not an interface. This is important to remember because you need to declare the class as abstract - otherwise it won't compile properly or you end up making your computer think this is a normal class .___. (Anyways shit's gonna hit the fan - soooo... maybe just do it right?)

Here you see, only the first method is abstract, because it has no body. 


O__O  BUT WHYYY

Fear no more - explanation is coming swift.
An abstract class must be declared as such, if it contains at least 1 abstract method. An abstract class can contain normal methods, such as isThisTrue() and goFlyAKite() in our example.

When you want to use the abstract class blueprint in a new class you are working on, you do so by writing the class signature and before opening the class body you add:
extends AbbyStracty
Then the compiler will automatically know that you intend to use the abstract methods from the abstract class AbbyStracty.

Btw. Once you extend an abstract class into a normal class, you must implement all abstract methods. But you also can extend an abstract class into another abstract class - which will then NOT force you to implement the abstract methods - you are making a 2. level abstract class which inherits the abstract methods from your extended abstract class.

Hope this was not so confusing, it took myself a while to get here!
Cheerio - summer is here!


Comments

Popular posts from this blog

How To - Citric Acid Cycle

How To - Determinants of Matrices

How To - CYK Algorithm