Java Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

 

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:

class Student { class DiplomaStudent {

private String name; private String name;


private int age; private int age;

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

This approach suggests that DiplomaStudent class is defined by copying the


attributes and methods of the Student class and then modifying the
DiplomaStudent class by adding the methods needed. This approach is not
sufficient as we are not making use the existing class. We have copied
„everything‰in Student class into DiplomaStudent class. Thus, the class
DiplomaStudent becomes longer. The relation that exists between Student class
and DiplomaStudent class is not shown in the DiplomaStudent class definition.
The relation is the inheritance relation.

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 extends ClassA {


 
 

  ClassB inherits ClassA. Thus, ClassB is subclass of


ClassA (superclass). ClassA shoud be
  implemented first before ClassB can inherits
ClassA.
 
Diagrammatically, if „classB extends classA‰, it could be illustrated as shown in
Figure 7.1:
 
classA
 

 
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:

  class Date extends Object {



  } is equivalent to
  Optional
  class Date {

 
}

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{

private String name;


private int age;

public void setName(String NAME) {


name=NAME;
}
public void setAge (int AGE) {
age=AGE;
}

public String getName () {


return name;
}

public int getAge(){


return age;
}

public void updateAge(int newAge){


age=newAge;
}
}

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:

class Policeman extends Person{

boolean promoted =false;

public void promotion(){


if (getAge() >= 45)
promoted=true;
else
promoted=false;
}

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 {

private String name;


private int age;
private String matricNumber;
public double fee=0.0;

public Student(String NAME,int AGE, String MATRIC) {


name=NAME;
age=AGE;
matricNumber=MATRIC;
}

public String getName () {


return name;
}

public int getAge(){


return age;
}

public String getMatric(){


return matricNumber;
}

public double getFees (){


return fee;
}
}

The above class can be executed in the following program:


166  TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)

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)

Next, we can define a DiplomaStudent class that describes a particular type of


student. The diploma students have the characteristics common to all students (as
shown in the class Student), plus some additional ones. We can make
DiplomaStudent inherit from Student with the following syntax: class
DiplomaStudent extends Student and then add new specific method(s)
and attribute(s) meant only for this DiplomaStudent class.
TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)  167

The complete program for the DiplomaStudent class is given below:

Program 7.5:

class DiplomaStudent extends Student {


private double labFees;
private int numberOfCourses;

//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

In Program 7.5, we have implemented class DiplomaStudent that inherits Student


class. Many more classes that represent other types of students such as
DegreeStudent and MasterStudent classes can be inherited from the Student class.
We will not going show you the implementation of the DegreeStudent and
MasterStudent classes but we will leave it as an exercise for you to try.

EXERCISE 7.1

Write the implementation of the DegreeStudent and MasterStudent


classes that will inherit the Student class.

7.2 USING THE super KEYWORD

  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

The above two ways will be elaborated in the following sections.

7.2.1 Calling Superclass's Constructor


The syntax to call the superclass's constructor from subclass is as shown below:

super()    this will call the constructor in the superclass which has no
argument
OR
170  TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)

super(arguments)    this will call superclass constructor that matches the


arguments.

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.
 

Thus, in Line 5 of the Program 7.5, the statement super(NAME,AGE,MATRIC)


actually invokes the constructor of the superclass. Notice that this super keyword
has 3 arguments which exactly matched with the number of the parameters in the
superclass constructor.

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.

      public DiplomaStudent(String NAME,int AGE, String MATRIC,


int COURSE, double LABORATORY_FEES) {

setTotalCourse(COURSE);
super(NAME,AGE,MATRIC); //ERROR
              setLabFees(LABORATORY_FEES);
      }

7.2.2 Calling Superclass’s Methods


Besides calling the superclass of the constructor, the keyword super also could be
used to invoke member methods from the superclass.

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:    }

The statement super.getFees( ) in Line 16 is actually invokes the getFees() method


available in the superclass. Any overridden methods could be in invoked in the
subclass by using the super keyword.
TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)  171

7.2.3 Relationship between Superclass Objects and


Subclass Objects
An object of a subclass can be treated as an object of its superclass. You know that
when an object is created, the corresponding constructor is called. Every subclass
constructor is required to call its direct superclassÊs constructor as their first task
either implicitly or explicitly. If no explicit call of superclass constructor is
specified in the subclass constructor, the default constructor (which has no
arguments) in the superclass is called.
 
ThatÊs why if you want your class to be inherited, it is a good idea to provide
no-argument constructor in this class to avoid programming error.
 
We will illustrate this by using the following programs (Program 7.6 ă Program
7.9) which shows three level of inheritance as depicted in the following diagram:
 
Level1
 

 
Level2
 

  Level3

Program 7.6:
 

public class Level1 {


public Level1( ){
System.out.println(„Level1constructor);
}
}
Program 7.7:

public class Level2 extends Level1 {


public Level2( ){
System.out.println(„Level2 constructor);
172  TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)

}
}

Program 7.8:

public class Level3 extends Level2{


public Level3( ){
System.out.println(„Level3 constructor);
}
}

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();
}
}

The output for the Program 7.9 is shown below:


 

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;

public Human (String n){


name=n;
}

public String getName(){

return name;
}
}

Program 7.11:
 

Line 1: class Teacher extends Human {


Line 2: private String id;

Line 3: public Teacher (String NAME, String ID){


Line 4: name=NAME;
Line 5: id=ID;
Line 6: }
Line 7: }

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

 In the constructor of Teacher class (which is a subclass), there is no reference to


the constructor of its superclass, therefore the default no-argument constructor
in the superclass would be called by the compiler. However, in Human class,
there is no such default constructor.

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:

Line 1: class Teacher extends Human {


Line 2: private String id;
Line 3: public Teacher (String NAME, String ID){
Line 4: super(NAME); //call the constructor of the superclass
Line 5: id=ID;
Line 6: }
Line 7: }

7.3 OVERRIDING METHODS


A subclass will inherit all attributes and methods of its parent class. In certain
situations, there are methods inherited by the subclasses in which the
implementation is not suitable for the subclass.

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.

7.4 OVERRIDING VERSUS OVERLOADING


You have learned method overloading in Topic 5. The difference between method
overloading and method overriding are given in the following table:
 
Method Overriding Method Overloading
A method in a superclass is redefined in its Is a way to provide more than one method
subclass using the same signature and with a same name. They are distinguished
same return type as in its superclass. by their signatures.
TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)  175

Consider the following programs will demonstrate the above two concepts:

Example of Method Overriding Example of Method Overloading


class A { class C {
public void display( ){ public void display( ){
System.out.println(„C#‰); System.out.println(„Java‰);
} }
} }
public class B extends A { public class D extends C {
public void display(){ public void display(String data){
System.out.println(„Hi‰); System.out.println(data);
} }
} }
class obj1 { class obj2 {
public static void main (String[] args){ public static void main (String[] args){
B b = new B(); D d = new D();
b.display(); d.display(„Hello‰); //subclass method
} d.display(); //superclass method
} }
Output: Hi }
Output: Hello
Java
Explanation: Explanation:
Observe that the method display has been Observe that the method display has been
redefined in class B. Notice that the included in the both C class and D class but
methods display() in the superclass and now they having different signatures:
subclass have same signature that is: public void display() (from class C)
public void display() public void display(String) (from
class D)
Thus, subclass has overridden the same
method declared in its superclass. The Thus, the method display() in the subclass is
statement b.display() in the main() method overloaded (not overridden). It means that
will invoke the display() method available the object of D can invoke either the
in the B class. Since B has overridden the display() method in the superclass or in the
method display() in its superclass, there is subclass depending whether a argument is
no way for object B to access the method provided or not during the method
display() in the superclass. invocation.
176  TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)

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:

class School extends Building {


}

Program 7.14:

class Building extends Architecture {


public void display(){
System.out.println(„Building‰);
}
}

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

The output for the Program 7.16 is shown below:

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
 

Figure 7.6: The inheritance hierarchy for the classes m1 till mn

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;

With this declaration, we can have not only

student = new Student();

but also

student = new DiplomaStudent();

or

7.6 USING protected ACCESS MODIFIER


As discussed in the previous topic, the scope for the private attributes and
methods are limited to the class that defines the element. Other than private and
public access control, we also have another type of access control, which is
protected. This access control is used in the inheritance. We can access the
protected methods and attributes not from its own class only, but it also allows
us to access it from any other classes which inherits that class.

As an example, consider Program 7.17(a). This program has defined a class


named Payment. This class has two protected attributes, dollar and cent. It
also has a protected method called centAmount() which does some calculation
and return the value.

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.

Program 7.17 (a)


class Payment {
protected int dollar, cent;

public Payment(int dollarValue, int


centValue) {
dollar = dollarValue;
cent = centValue;
}

protected long centAmount( ) {


return dollar * 100 +cent;
}
}

Program 7.17 (b)


class PaymentCheque extends Payment {
private String nbrCheque;

public PaymentCheque(int dollarValue, int


centValue, String chequeNo) {
dollar = dollarValue;
cent = centValue;
nbrCheque =chequeNo;
}
}
TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)  181

Program 7.17 (c) (Contains error)

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( );
}
}

7.7 USING final KEYWORD


Sometimes we donÊt want the class that we have created to be inherited by other
classes or we donÊt want a method in a superclass to be overridden by its
subclass. In Java, the final keyword is used for these purposes. Class declared
as final cannot have subclasses. It means other classes cannot inherit the class.
Method declared as final cannot be overridden by other subclasses.

Consider the following programs:


 

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

public void display (){


System.out.println(„Hello‰);
}
}

7.8 ABSTRACT CLASSES AND ABSTRACT


METHODS
 

When discussing inheritance, we cannot avoid on discussing abstract and


concrete classes. An abstract class is a class that never has any objects but can be
inherited by other class. Consider this: would it make sense to have an object
Fruit? Clearly not, as the class Fruit is an abstraction of a fruit, and not a fruit
itself. In this case, Fruit is an abstract class and we cannot create object for this
class.

A concrete class is class that has objects. Up until this topic, all the classes we
have discussed were concrete classes.

Returning to abstract classes, if we cannot create object from an abstract class,


why then we may have abstract class in our program? Actually, each abstract
class represents some idea, although it will not be totally complete as some
details and definitions will be left out to the concrete classes that inherit from the
abstract class. The name of the abstract class should reflect that itÊs a concept
rather than something specific. So ÂAccountÊ versus ÂChecking AccountÊ, or
ÂVehicleÊ versus ÂTruckÊ. Note that abstract classes should not inherit from
concrete classes, as it makes no sense to go from general to specific and back to
general. For example consider the following class:
TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)  183

Program 7.20:

public  abstract  class K1 { 

…. 

 ….      Notice that K1 is an abstract class

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

1. Consider the following two classes:

public class ClassA {


public void methodOne(int i) {
}
public void methodTwo(int i) {
}
public static void methodThree(int i) {
}
public static void methodFour(int i) {
}
}

public class ClassB extends ClassA {


public static void methodOne(int i) {
}
public void methodTwo(int i) {
}
public void methodThree(int i) {
}
public static void methodFour(int i) {
}
}

(a) Which method overrides a method in the superclass?


(b) Which method hides a method in the superclass?
(c) What do the other methods do?
TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)  185

2. Consider the following class definition:


class X {
protected int atrib1;

public X(int nilai) {


atrib1=nilai;
}
public int kira(int nilai){
int hasil = 1;
for (int i=0; i<atrib1;i++)
hasil=hasil*nilai;
return hasil;
}

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;
  }

  public void setNilaiAsal( ) {


nilai = nilaiAsal;
  }
  }
  State whether the concepts of method overriding and method overloading
  have been used in the above program. Explain your answer.
 
 
 
 
 
 
 
 
TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)  187

 
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);
  }
  }

  Create a class called Employee whose objects are records for an


  employee. This class will be a derived class of the class Person above
  which you will have to copy into a file of your own and compile. An
  employee record has an employee's name (inherited from the class
Person), an annual salary represented as a single value of type double,
  a year the employee started work as a single value of type int and a
  national insurance number, which is a value of type String.
 
  Your class should have a reasonable number of constructors and
member methods to retrieve the attributes value, as well as an equals
 
method. Write another class containing a main method to fully test
  your class definition.
 
 
188  TOPIC 7 OBJECT ORIENTED PROGRAMMING (PART III)

 
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

abstract classes method overriding


concrete classes polymorphism
final protected
inheritance super

You might also like