Inheritance is when you make an
extension of a class. This extension is called the child class of the parent.
You can extend a class, by writing extends (parent_class_name). When you make a
child class that gives the class access to all the methods in the parent class.
Inheritance is used when you want to add new methods to the parent class. So
the child class is the parent class plus a little more. Some classes can’t be extended,
like the String class which is a final class.
Another thing you can do in a child
class, is override methods in the parent class. When overriding a method, the
header of the method has to be the same. You can then change what the method
does in the child class. So whenever you call that method in the main class, to
a child class object it does the override method. If you put @Override before
overriding a method the program will make sure that the method is overriding a
method in the parent class. So it will make sure you don’t spell the parent
method wrong, and just end up creating a totally new class.
Sometimes you won’t be able to
access every part of a parent class. For example if you declare an instance
variable private it is only accessible in that class. So you won’t be able to
use that variable in the child class. You can get rid of private which allows
access to that variable with in the package of the class. So if the child class
is within the package of the parent class it has access to that variable.
Lastly if you make an instance variable protected, you can access the variable
anywhere in the package of the class, and in the child classes.
No comments:
Post a Comment