Ineheritance
Inheritance in Java
-
Inheritance in Java is very simple and is handled by the "extends" keyword.
As you might expect, subclasses work just like (inherit all of the functionality)
their superclass except that they typically add extra funtionality.
If a class does not specifically extend anything
then it will be automaticaly extended from the root Object class |
-
Thus, in the following example, we create a subclass of Applet called myApplet:
public class myApplet extends Applet
{
...new fields and methods...
}
Further, extension is transitive. That is if you extend from a class which
is an extension of another, then you gain the functionality of your superclass
as well as its superclass.
It is also worth noting that not only can you add to the functionality
of a superclass, but you can modify existing functionality as well. This
is achieved by overriding the method in the subclass. To override a superclass'
method, you would implement your own method with the same signature as
your superclass' method. Thus, the Java Virtual machine would use your
implementation rather than your superclass'. Of course, you can explicitly
use your superclass' methods and fields using the "super" keyword such
as:
super.methodname();
The super keyword is particularly important when working with Constructors
because subclasses do not inherit the constructors of their superclasses.
Thus, in order to utilize the constructor of your superclass, you must
explicitly call it using the super keyword such as in the following example:
class myFrame extends Frame
{
public myFrame()
{
super();
}
public myFrame(String title)
{
super(title);
}
...the rest of your methods and fields....
}
Java also provides the "final" keyword which prevents
a class from being subclassed, a method from being overridden and a variable
from changing its initialized value. |
Additional Resources:
Operator
Overloading (Polymorphism in Java)
Table of Contents
Packages
|