Inheritance & Visibility
I managed to keep my last post about inheritance relatively short, and I’m going to do the same for this post. I think it’s easier to digest little bits of information at a time. This post will cover a little bit more about inheritance and also visibility.
First, we will continue learning more about inheritance.
An abstract class is a class that can be extended, but not instantiated. So, we may not want people to instantiate the Person class and require they instantiate a class that extends the Person class, like the Boy class. Below is an example of the Person class without the guts.
Don’t get abstract classes confused with interfaces. Abstract classes can contain the guts of a method; Interfaces can only define the name/parameters of the methods.
You can not extend a final class. Final classes can be useful when you want to put some restriction on the extension of a class. You can also create a final method in any class so that no one can override it. Below is an example of a final class and a final method.
So far we have made everything public, which is fine while we learn. I wouldn’t mind having invisibility as a super hero power.
Public indicates that you can access it directly after instantiating the class as shown below.
Protected restricts the usage to the inside of the class. It also allows other classes that extend the class that declared the property or method as protected to access it. That is confusing, and I hope the example below helps.
That example covered public and protected methods. It also covered protected properties. We weren’t able to alter the age property directly, but we were able to change it by using the public method setAge(). When we used the setAge() method, it called the protected method status(), which output a message for us.
So anything public is like living in the “Wild Wild West” with Will Smith. You can set it, call it, and update it. Anything protected can only be used by that class or any class that extends it.
You can only use a private method or property in the class that initially declared it. Classes that extend that class can not use it. You can not update it or use it outside of that class. Below is an example of a private method and property.
Okay, this post turned out to be longer than I originally planned. Maybe I shouldn’t have used a Will Smith movie as a reference. Send me an email if you have any questions or if I have any typos.
Will Smith is an amazing actor. I’m an expert on dogs and people.