Java Notes
Java Notes
Java Notes
Topic Object
7 Oriented
Programming
(Part III)
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Describe the meaning of inheritance;
2. Differentiate between method overloading and method overriding;
3. Write Java programs that have inheritance capability;
4. Describe the meaning of protected access modifier;
5. Write Java programs that have polymorphism capability; and
6. Descibe the meaning of final, abstract and super keywords.
INTRODUCTION
Inheritance is the capability of a class to use the properties and methods of
another class while adding its own functionality. An example of where this could
be useful is with an employee records system. You could create a generic
employee class with states and actions that are common to all employees. Then
more specific classes could be defined for salaried, commissioned and hourly
employees. The generic class is known as the parent (or superclass or base class)
and the specific classes as children (or subclasses or derived classes). The concept
of inheritance greatly enhances the ability to reuse code as well as making design
a much simpler and cleaner process.
160 TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)
Subclasses have all the characteristics and behaviour inherited from the superclass
but have added some more characteristics and behaviours for themselves. For
example, after we have created Student class, we could also define another classes
for diploma students, master students, etc in which all will inherit the Student
superclass. It would involve a lot of effort to create brand new class. However, it
would be easier if we could take an existing, clone it and then make modifications
to the clone to reflect the extra functionality. This is what we do with inheritance.
Consider the following two classes which donÊt use any inheritance:
public DiplomaStudent(String
public Student(String NAME, int NAME,int AGE) {
AGE) { name=NAME;
name=NAME; age=AGE;
age=AGE; }
}
public String getName () {
public String getName () { return name;
return name; }
}
public int getAge(){
public int getAge(){ return age;
return age; }
}
} public double computeFees(int
totalSubject)
{
return (totalSubject*50.00);
}
}
Explanation:
Notice that the DiplomaStudent class has all the attributes and methods of
Student class (except the constructor method of the Student class). The only
methods added in DiplomaStudent class are computeFees() and a constructor
method.
TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III) 161
7.1 INHERITANCE
Inheritance is one of the most important concepts in object-oriented programming.
It enables us to write a class that is similar to an existing class, but that still has
some of its properties. To create the new class, you only have to specify how that
class is different from the existing class. The inheritance gives you an automatic
access to the existing class.
The keyword extends followed by class names indicates the class from which the
new class inherits an existing class. For example:
classB
Figure 7.1: Diagrammatically showing classB inherits classA
162 TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)
If we have another classC that extends classA, then we would have the following
diagram:
classA
classB classC
Figure 7.2: Diagrammatically showing classB and classC that inherits classA
Observe from Figure 7.2 that a superclass can be inherited by more than one
different classes but a subclass can only inherits one superclass.
Take Note⁄.
Every class in Java is automatically is a subclass of Object. It means Object is
the superclass of all the classes in Java irrespective whether the class is library class
or user defined class. For example, consider the Date class in Program 6.6 (Topic 6).
The Date class actually is a subclass of the class Object but we are not required to
write „extends Object‰ explicitly in the program as shown in the example
below:
While all classes in Java inherit Object class by default, the programmer also can
give capability for a class to extend other class. Now let us see of how we can
inherit a user defined class. Example: „class Policeman extends Person‰ means
Policeman is a subclass inheriting Person (which is a superclass). Now observe the
following class definition of Person:
TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III) 163
Program 7.1:
class Person{
In this base Person class, a Person is defined by its private data, such as name and
age. These data are generic to every type of person. The private attributes in the
Person class can be manipulated by the public methods such as getName(),
getAge(), setName(), setAge() and updateAge(). The attributes and methods are all
encapsulated in the class. Furthermore, the attributes are private in this class. It
means they cannot be directly accessed from outside of the class. Only the classÊs
public methods can access the attributes. By adopting this strategy, users cannot
retrieve or update the value the private attributes directly. But this is possible with
the public methods available in the class. This shows how encapsulation works.
Do you know⁄
Public methods such as getAge(), getName(),etc that returns the value of a
private attribute are known as accessors while public methods such as
setAge(..), setAddress(..), etc that assign a value to the private attributes are
known as mutators.
164 TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)
Now suppose you want to have create class for Policeman. We want ensure that
the policemen is promoted when he/she is 45 years of old. Thus we could have
new class Policeman that inherits the class Person thus releasing the burden of
rewriting the codes of the personal information.
Program 7.2:
Observe that Program 7.2 is much smaller than the superclass (Program 7.1) as it
implicitly inherits all the attributes and methods (except private attributes) from
the superclass Person. Besides promotion() method, the subclass Policeman has all
other methods from the superclass like setName(), setAge(), getName(), getAge()
and updateAge().
Now, let us see another example. Assume that you need to maintain student
records in a university. The university has several different types of students:
diploma students, degree students and master student and your program should
be able to handle all of these students.
In order to solve this problem, we can define a general class of Student that has
attributes for name, age, matric number, etc which is common to all the students.
However, at the same time, each type of student requires slightly different
information such as fees calculation which is calculated using different formula for
each type of the student (diploma students fees is calculated based on number of
courses taken in a semester plus the laboratory fees, degree students fees is fixed
while masters student fees is calculated based on number of courses taken in a
semester and research fees).
We can define a class called Student that describes the common characteristics of
all students. For example:
TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III) 165
Program 7.3:
class Student {
Program 7.4:
class obj {
public static void main (String[ ] args ) {
Student std= new Student(„Ali‰, 26, „S235‰);
System.out.println(„Name is „+ std.getName() );
System.out.println(„Age is „+ std.getAge ());
System.out.println(„Matric is „+ std.getMatric() );
System.out.println(„Fee is „+ std.getFees() );
}
}
The output of the above program is given below:
Name is Ali
Age is 26
Matric is S235
Fee is 0.0
In the computer memory, the object std will hold the following values as shown in
Figure 7.3:
std name = Ali
age = 26
matricNumber = S235
fee = 0.0
Figure 7.3: The state of the object std (object of the Student class)
Program 7.5:
//constructor
public DiplomaStudent(String NAME,int AGE, String
MATRIC, int COURSE, double LABORATORY_FEES) {
super(NAME,AGE,MATRIC); /*call the superclass’s
constructor */
setTotalCourse(COURSE);
setLabFees(LABORATORY_FEES);
}
public void setTotalCourse(int c){
numberOfCourses=c;
}
public void setLabFees(double lab){
labFees=lab;}
public double getFees(){
fee= (super.getFees())+(numberOfCourses*50.00 + labFees);
return fee;
}
}
The above class can be executed in the following program:
Program 7.6 (a):
class obj {
public static void main (String[ ] args ){
DiplomaStudent dip= new DiplomaStudent(„Ahmas‰, 26, „S135‰, 3, 65.00);
System.out.println(„Name is „+ dip.getName() );
System.out.println(„Age is „+ dip.getAge() );
168 TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)
System.out.println(„Matric is „+ dip.getMatric() );
System.out.println(„Fee is „+ dip.getFees() );
}
}
The output for the above program is given below:
Name is Ahmad
Age is 26
Matric is S135
Fee is 215.0
In the computer memory, the object dip will hold the following values as shown in
Figure 7.4:
name = Ahmad
age = 26
dip
matricNumber = S135
fee = 215.0
labFees = 65.00
numberOfCourses = 3
Figure 7.4: The state of the object dip (object of the DiplomaStudent class which inherits
Student class)
Compare Figure 7.3 and Figure 7.4. Can you see any difference?
Take note⁄
Note that subclass can access all the public and protected methods and attributes
in the superclass but not vice versa as shown in the following program:
class obj {
public static void main (String[ ] args ){
Student std= new Student(„Ali‰, 26, „S235‰); //OK
DiplomaStudent dip= new DiplomaStudent(„Ali‰, 26, „S235‰, 3, 65.00);
//OK
System.out.println(„Name is „+ dip.getName() ); //OK
System.out.println(„Age is „+ dip.getAge() ); //OK
std.setTotalCourses(5); /* ERROR! SUPERCLASS CANNOT ACCESS ITS
SUBCLASS METHODS AND ATTRIBUTES */
}
}
TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III) 169
EXERCISE 7.1
Did you notice the usage of super keyword in Line 5 and Line 16 of Program
7.5? What does that super statement do?
A subclass inherits all attributes and methods from the superclass provided the
methods and attributes in the superclass are public or protected (protected will be
elaborated in section 7.6). How about constructor in a superclass? Can subclass
inherits or invokes the constructor of the superclass? The answer is CANNOT.
Subclass cannot inherits or invoke the constructor of the superclass even tough
constructor is declared as public. But subclass can call the constructor of the
superclass through the super keyword. Actually, the keyword super could be
used in the following ways in a subclass:
To call a superclass's constructor
To call a superclass's method
super() this will call the constructor in the superclass which has no
argument
OR
170 TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)
You must use the keyword super if you want to invoke the superclass
constructor from a subclass. You cannot invoke the superclass constructor in a
subclass by its name.
One constraint that we face when we use the super keyword in executing the
constructor method of parent class as explained above is that it must be the first
statement of the subclass constructor method. Therefore, if we swap line 5 and
line 6 in the constructor method of Program 7.5 such as shown below , the Java
compiler will give a compilation error.
setTotalCourse(COURSE);
super(NAME,AGE,MATRIC); //ERROR
setLabFees(LABORATORY_FEES);
}
For example, observe the following lines taken from Program 7.5:
Line 15: public double getFees(){
Line 16: return (super.getFees())+(numberOfCourses*50.00 +
labFees);
Line 17: }
Level2
Level3
Program 7.6:
}
}
Program 7.8:
Now let us write that program that will create the object of the Level3 class shown
above:
Program 7.9:
class obj {
public static void main (String[ ] args ){
Level3 l3 = new Level3();
}
}
Level1 constructor
Level2 constructor
Level3 constructor
You could see that the construction happens from the base „outward‰ so the base
class is initialised before the derived class can access it. Now let us consider
another example:
TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III) 173
Program 7.10:
class Human {
private String name;
return name;
}
}
Program 7.11:
Observe that class Teacher in Program 7.11 inherits class Human in Program 7.10.
The Program 7.11 has two major errors:
Although Teacher inherits the attribute name from class Human but it cannot
access it because attribute name is private to the class Human. Therefore, the
statement in Line 4 (of Program 7.11) is invalid
Thus, in order to fix the above problem, we must invoke the constructor of the
superclass explicitly as shown below:
174 TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)
Program 7.12:
Consider the Program 7.3 (which has Student class ) and Program 7.5 (which has
DiplomaStudent class). Notice that DiplomaStudent is a subclass of
DiplomaStudent. Notice also that both classes have the method getFees() (of
course with different implementation). By declaring the getFees() method, the
class DiplomaStudent has override the getFees() method in the superclass. Thus,
when an object of DiplomaStudent invokes the method getFees(), it will invoke
the one available in the DiplomaStudent class.
Take note⁄
Private methods in the superclass cannot be overridden in the subclass. If a
method declared in a subclass is a private method in its superclass, then two are
not related to each other. Static methods can be inherited but cannot be
overridden. If a static method defined in superclass is redefined in the subclass,
then the static method defined in the superclass is hidden.
Consider the following programs will demonstrate the above two concepts:
7.5 POLYMORPHISM
Polymorphism is very much related to inheritance. A program will be easy to
extend if we use polymorphism in our program. Polymorphism is the capability
of an action or method to do different things based on the object that it is acting
upon. Note that polymorphism does not imply that objects change class. It means
that the exact code of the method will change according to the class of the object
that receives the message. To demonstrate polymorphism, consider the following
program.
Program 7.13:
Program 7.14:
Program 7.15:
class Architecture {
public void display(){
System.out.println(„Architecture‰);
}
}
TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III) 177
Program 7.16:
class obj {
public static void main (String[ ] args ){
School school = new School();
school.display(); //this is polymorphic call
Building building = new Building();
building.display();
Architecture architecture = new Architecture();
architecture.display();
}
}
The inheritance hierarchy for the classes School, Building and Architecture are
shown in Figure 7.5 below:
Architecture
Building
School
Figure 7.5: The inheritance hierarchy for the classes School, Building and Architecture
Building
Building
Architecture
How the compiler managed to get the above output? Here is the explanation.
Classes School, Building and Architecture have their own implementation of
display method(). Which method will be invoked is determined dynamically by
178 TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)
the compiler during the runtime. This capability is called dynamic binding or
polymorphism. It works like this:
Let say p is an object of the class m1 and at the same time we have other classes
such as m2, m3, ⁄⁄⁄, mn-1 and mn in which m1 is the subclass of m2, m2 is
the subclass of m3,⁄⁄., mn-1 is the subclass of mn. . So the inheritance hierarchy
is like Figure 7.6 below:
mn most general class
mn‐1
:
:
m3
m2
m1 most specialized class
Thus, mn is the most general class while m1 is the most specific class. If p
invokes the method o, the compiler will search for this method in the order of
m1, m2 and m3, mn-1 and mn until the method is found. Once the method is
found, the search stops and that method in the appropriate class will be invoked.
ThatÊs way when school.display() is invoked in Program 7.16, the display method
defined in the Building class is used as the School class does not have its own
display() method.
TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III) 179
TAKE NOTE⁄
In section 6.4 (Topic 6), you have learned about reference type variables. When
we declare a reference type variable using a particular class name, it can be used
to refer to any object of that class or it also can refer to any object of any class
that is related through its inheritance relationship. For example, if Student is
the superclass for DiplomaStudent and MasterStudent and we have the
following declaration:
Student student;
but also
or
Since the attribute and the method have been declared as protected in Payment
class, it can be accessed from the Payment class and its subclass such as
PaymentCheque class defined in Program 7.17(b).
180 TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)
The direct access to the superclass attributes declared as protected was shown
in constructor method in PaymentCheque class. As you can see, super is not used
in this method to invoke the superclass constructor to assign value for the
attributes. This is because class PaymentCheque can directly access the attributes of
Payment class as the attributes are declared as proctected.
Now, letÊs look at the main( ) method in the Program 7.17(c). Object payment which
is object of the class PaymentCheque has been created with appropriate
arguments. Then the object invokes the method centAmount(). This is an
error because method centAmount( ) is declared as protected. Thus, it could
only be invoked in its class and from all its subclasses. The Program 7.17(c) does
not inherits class Payment and its considered to be outside from the inheritance
hierarchy of Payment class.
class obj3 {
public static void main (String[ ] args ) {
PaymentCheque payment = new PaymentCheque (3, 20, ‰0053867‰);
// The f ol l o w in g statement contains ERROR
System.out.println(„Amount(cent):„+ payment.centAmount( );
}
}
Program 7.18:
public final class A {
⁄.
⁄. ERROR! Class B cannot extends
class A because class A is a final
}
class
class B extends A {
⁄.
⁄.
}
182 TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)
Program 7.19:
class M1 {
public final void display (){
System.out.println(„Hi‰);
}
ERROR! Method display() cannot
} be overridden because it is
class M2 extends M1 { declared as final in the superclass
A concrete class is class that has objects. Up until this topic, all the classes we
have discussed were concrete classes.
Program 7.20:
public abstract class K1 {
….
}
Program 7.21:
class K2 extends K1 {
No problem! K2 can inherits K1
⁄. which is an abstract class
⁄.
}
Program 7.22:
class obj {
public static void main (String[ ] args ){
K1 k1 = new K1(); /* ERROR! CANNOT CREATE OBJECT FROM AN
ABSTRACT CLASS */
K2 k2 = new K2(); /* NO PROBLEM */
}
}
Besides abstract classes, you may also have abstract methods in your class
program. An abstract method is a method signature (that may have parameters)
but without implementation. Its implementation is provided by the subclasses. A
class that contains abstract methods must be declared abstract. Remember that an
abstract method is non-static and cannot be included in a non-abstract class. If a
subclass of an abstract superclass does not implement all the abstract methods,
the subclass must be declared abstract.
184 TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)
EXERCISE 7.2
class Y extends X {
public Y (int nilai) {
super(nilai);
}
public int kira(int nilai){
int hasil=0;
for (int i=0; i<atrib1; i++)
hasil=hasil+nilai;
return hasil;
}
}
Write the output for the following application:
class aplikasi {
public static void main (String[ ] args) {
Y pengira = new Y(2);
for (int i=1; i<3; i++){
int hasil =pengira.kira(i);
System.out.print(hasil+ “”);
}
}
}
186 TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)
3. Consider the following program:
class Penokok {
protected int nilai;
public Penokok(int nilaiMula) {
nilai = nilaiMula;
}
public void tokok() {
nilai++;
}
public int nilainya() {
return nilai;
}
}
class Pembilang extends Penokok {
private int nilaiAsal;
public Pembilang(int nilaiAwal) {
super(nilaiAwal);
nilaiAsal = nilaiAwal;
}
4. Consider the following class:
public class Person
{
private String name;
public Person()
{
name = "No name yet.";
}
public Person(String n)
{
name = n;
}
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
public void print()
{
System.out.println("Name: " + name);
}
public boolean equals(Person p)
{
return name.equals(p.name);
}
}
5. Consider the following constructor method:
public ConferenceRoom(int rent, int cap){
super(rent,cap);
}
State the purpose of the statement super(rent,cap) that exist in the method.
Assume ConferenceRoom is a subclass.
6. Consider the following class definition:
class Pembilang {
protected int nilai;
public Pembilang() {
nilai = 0;
}
public Pembilang(int nilaiAwal) {
nilai = nilaiAwal;
}
public void kemaskini() {
nilai++;
}
public int nilainya() {
return nilai;
}
}
Write a class definition for Pemasa class which extends Pembilang class to
do the decreasing calculation and display the message „Ring⁄Ring⁄‰
when the value reaches zero.
TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III) 189
Inheritance is a type of relationship among classes, where one class shares the
structure or behaviour defined in one (single inheritance) or more (multiple
inheritance) of the other classes.
The idea that different classes have shared common characteristics is explained
by the concepts of superclasses, subclasses and inheritance.
We can illustrate these concepts by seeing student as the superclass, in which
different subclasses such as diplomaStudent and mastersStudenrt with varying
characteristics inherited from it.
Subclasses have all the characteristics and behaviour inherited from the
superclass but have added some more characteristics and behaviours.
When discussing about inheritance, the following concepts cannot be
avoided:
‐ Polymorphism
‐ Method overriding
‐ Abstract and concrete classes
‐ The usage of super and final keywords
‐ Protected access modifier