Java Home : www.sharetechnote.com |
||||||||||||||
Java - Class - Extends
The power of OOP (Object Oriented Programming) is the capability of creation of a new class based on an existing class and of extending / modifying an existing class. At the center of this capability is the function called 'Extends'. In the standard OOP terminology, 'Extends' refers to 'Inheritance'. (I would not talk too much about the OOP theory. I would rather let you absorb the concept by hands-on / practice).
All Classes in single file
This example shows the most basic example of creating a class uisng 'Extends'. This is just to show of the syntax of 'Extends' and in practice the class does not have any useful functionality.
The part you I want you to focus on is highlighted in color. It means 'create a class named ChildClass and the ChildClass inherits all the functionality of another class named ParentClass'. Both ParentClass and ChildClass has only one special member function (method) called Creator function'. You can see how these two classes interplays at the result.
In the main() function, only the ChildClass object is created, but you would notice that creator function of both ParentClass and ChildClass are called. From the order of the print out, you will notice that when the ChildClass creator function is executed, it calls the ParentClass creator function first and then executes the creator function of the ChildClass.
C:\temp>java ExampleExtend01
Constructor of Parent Constructor of Child
All Classes in separate file
In terms of functionality, this example is same as the previous example. What I want to show is just to show that you can put each of the classes in a separate files.
C:\temp>java ExampleExtend01
Constructor of Parent Constructor of Child
Inherit Parent Method
C:\temp>java ExampleExtend02
Constructor of Parent <-- Printed by ParentClass() called by new ParentClass() Constructor of Parent <-- Printed by ParentClass() called by new ChildClass() Constructor of Child <-- Printed by ChildClass() called by new ChildClass() ParentClass.printString() <-- Printed by pc.printString() ParentClass.printString() <-- Printed by cc.printString()
Override Parent Method
C:\temp>java ExampleExtend03
Constructor of Parent Constructor of Parent Constructor of Child ParentClass.printString() ChildClass.printString()
Add New Methods
C:\temp>java ExampleExtend04
Constructor of Parent Constructor of Parent Constructor of Child ParentClass.printString() ChildClass.printString() ChildClass.printNumber()
|
||||||||||||||