Previous Page |Next Page
- 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 extendanything than it will be automaticaly extended from the root Object class|
- Thus, in the following example, wecreate a subclass of Applet caled myApplet:
public class myApplet extends Applet
...new fields and methods...
- Further, extension is transitive. Thatis if you extend from a class which is an extension of another, then you gain the functionality of your superclass as well as itssuperclass.
- It is also worth noting that not onlycan you add to the functionality of a superclass, but you can modify existing functionality as well. This is achieved through overriding a method in one's superclass. To override asuperclass' method, you would implement your own method with thesame signature as your superclass' method. Thus, the JavaVirtual 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:
- The super keyword is particularly important when working with Constructors because subclasses do notinherit the constructors of their superclasses. Thus, in orderto utilize the constructor of your superclass, you must explicitlycall it using the super keyword such as in the following example:
class myFrame extends Frame
public myFrame(String title)
...the rest of your methods and fields....
|Java also provides the "final" keywordwhich prevent a class from being subclassed, a method from being overridden and a variable from changing itsinitialized value. However, it is rarely used for regular application code.|