Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

Lab Manual for Advance Computer Programming

Lab-04
Abstract classes and Interfaces
Lab 4: Abstract Classes and Interfaces

Table of Contents
1. Introduction 36

2. Activity Time boxing 37

3. Objective of the experiment 37

4. Concept Map 37
4.1 Super class 37
4.2 Encapsulation 37
4.3 Abstract class 38
4.4 Abstract method 38
4.5 Interface 38
4.6 Extending Interfaces 39

5. Homework before Lab 39


5.1 Problem Solution Modeling 39
5.2 Practices from home 40
5.2.1 Task-1 40
5.2.2 Task-2 40

6. Procedure& Tools 40
6.1 Tools 40
6.2 Setting-up JDK 1.7 [Expected time = 5mins] 40
6.2.1 Compile a Program 40
6.2.2 Run a Program 40
6.3 Walkthrough Task[Expected time = 30mins] 40
6.3.1 Implementing Abstract Class 41
6.3.2 Implementing Interfaces 42

7. Practice Tasks 43
7.1 Practice Task 1 [Expected time = 10mins] 43
7.2 Practice Task 2 [Expected time = 15mins] 43
7.3 Practice Task 3 [Expected time = 15mins] 43
7.4 Practice Task 4 [Expected time = 10mins] 44
7.5 Practice Task 5 [Expected time = 10mins] 44
7.6 Out comes 44
7.7 Testing 44

8. Evaluation Task (Unseen) [Expected time = 55mins for two tasks] 44

9. Evaluation criteria 45

10. Further Reading 45


10.1 Books 45
10.2 Slides 45

Department of Computer Science, Page 35


C.U.S.T.
Lab 4: Abstract Classes and Interfaces

Lab4: Abstract classes and Interfaces

1. Introduction

You have learnt Java constructs, abstract classes and interfaces. In this lab, you will test the
theory by implementing the abstract classes and interfaces. A class in which one or more method
is declared but not defined is known as abstract class. Any method which is declared but not
defined is known as abstract method. Following example shows how to declare an abstract class.

public abstract class Animal {


private String type;
public abstract void sound(); // Abstract method
public Animal(String _type) {
type = new String(_type);
}
public String toString() {
return “This is a “ + type;
}
}

For the above class we cannot create an object as it is an abstract class and the class inheriting
this abstract class must define the methods which were declared but not defined in the class. On
the other hand, in an interface all the methods are abstract. Therefore, instead of defining all the
methods abstract a simple way is to replace the “class” keyword with “interface”.

For example, remote controlfor multimedia devices has some common functionalities to be
performed. As you know that there are many appliances commonly used in home that have some
common features and anyone who will use any remote will expect some common features to be
in a remote. This means that remote is some standardized thing. If you try to define a common
interface for remote then it might look as follows.

interface Remote {
void volumeDown();
void volumeUp();
void forward();
void rewind();
}

Any class which uses this interface must implement all its methods. Based on need and
requirement any class can use this interface by using the keyword “implements” instead of
“extends”. It is important to note here that after “implements” keyword we can use as many
interfaces as we like but any class can extend only one class. Multiple inheritance that was
supported by C++ has been removed by Java.

Department of Computer Science, Page 36


C.U.S.T.
Lab 4: Abstract Classes and Interfaces

Relevant Lecture Material

a) Revise Lecture No. 3 and 4


b) Text Book: Java: How to Program by Paul J. Deitel, Harvey M. Deitel
1. Read pages: 474-494
2. Revise the object oriented concepts of inheritance, abstract classes and
polymorphism.

2. Activity Time boxing

Table 1: Activity Time Boxing


Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 20mins 20mins
6.2 Setting-upPath for JDK 5mins 5mins
6.3 Walkthrough Tasks 30mins 30mins
7 Practice tasks 10 to 15mins for each task 60mins
8 Evaluation Task 60mins for all assigned task 55mins

3. Objective of the experiment

 To get basic understanding of Object Oriented concepts and how they are implemented
using Java.
 To write programs for polymorphic scenarios and learn how to compile and run it
 To get an understanding of identifying basic errors.
 To understand the command line arguments and their purpose.

4. Concept Map

This section provides you the overview of the concepts that will be discussed and implemented
in this lab.

4.1 Super class

Any class which is extended or in other words inherited is known as base class. In Java, the base
class is called the super class. You can initialize the fields of super class by calling super()
method, which calls the constructor of the super class.

4.2 Encapsulation

In simple terms, encapsulation means data hiding. Encapsulation provides a layer of control to
the class for its private fields. Normally, we use setter and getter methods to maintain the
encapsulation rules.

Department of Computer Science, Page 37


C.U.S.T.
Lab 4: Abstract Classes and Interfaces

4.3 Abstract class

Abstract classes are used to define only part of an implementation. Because, information is not
complete therefore an abstract class cannot be instantiated.

Like simple classes, abstract class can also contain instance variables and methods that are
completely defined. The class that inherits an abstract class must provide detailsi.e.
implementation of undefined methods.

4.4 Abstract method

A method that has no implementation similar to pure virtual function in C++. Any class with an
abstract method must be declared abstract. If a subclass provides implementation of all abstract
methods of the super class, only then we can create an object of subclass. Such class is also
known as concrete class.

It is important to understand that the reference of abstract class can point to its sub class that is
concrete class. This concept gives rise to the concept of dynamic binding studied in OOP course.

4.5 Interface

Similar to Abstract class, interfaces impose a design structure on any class that uses the interface.
Unlike inheritance, a class can implement more than one interface. To do this; separate the
interface names with commas. This is Java’s way of multiple inheritance.

class Student implements Displayable, Printable

We cannot instantiate object of interface like the abstract classes. Figure 1 shows characteristics
of an interface

Figure 1: Characteristics of Interface

However, a reference of interface can point to any of its implementation class. Static methods

Department of Computer Science, Page 38


C.U.S.T.
Lab 4: Abstract Classes and Interfaces

cannot be declared in the interfaces.

You can choose to omit implementing the few methods declared in interface but in this scenario
a class implementing the interface will become an abstract class and you will have to explicitly
mention abstract keyword in the definition of such class.

public interface TestInterface {


public void myMethod1();
public void myMethod2();
}

abstract public class interfaceExample implements TestInterface {


public void myMethod1(){
}
}

4.6 Extending Interfaces

Java allows one interface to extend or inherit another interface. Following example shows how to
do that.

public interface Interface1 {


double Value = 20.4;
}

public interface Interface2 extends Interface2 {


double method1 (double _value);
}

5. Homework before Lab

You must solve the following problems at home before the lab.

5.1 Problem Solution Modeling

After reading the reference material mentioned in the introduction, now you are ready to perform
homework assigned to you

5.1.1 Problem description:

Write down an example to elaborate simple extension and then polymorphism and how it can be
implemented in Java.

Department of Computer Science, Page 39


C.U.S.T.
Lab 4: Abstract Classes and Interfaces

5.2 Practices from home

Solve the following subtasks.

5.2.1 Task-1

Make a list of differences in abstract classes and interfaces in Java.

5.2.2 Task-2

Identify the scenarios (at least two examples from daily life)for usinginterfaces.

6. Procedure& Tools

6.1 Tools

Java Development Kit (JDK) 1.7

6.2 Setting-up JDK 1.7 [Expected time = 5mins]

Refer to Lab 1 sec 6.2.

6.2.1 Compile a Program

Use the following command to compile the program.

javac Interface.java

After the execution of the above statement bytecode of your class will be generated with same
name as the .java file but its extension will change to .class.
Similarly, compile all classes implementing the interfaces.
Now you will need JVM to run the program.

6.2.2 Run a Program

After successfully completing the section 6.2.1, the only thing left is to execute the bytecode on
the JVM. Run the file containing main method in it. Use the following command to run the
program.

java DriverClass

If the above command executed successfully then you will see output of the program.

6.3 Walkthrough Task[Expected time = 30mins]

This task is designed to guide you towards creating your own abstract class and interface and
running the program.

Department of Computer Science, Page 40


C.U.S.T.
Lab 4: Abstract Classes and Interfaces

6.3.1 Implementing Abstract Class

This example shows you how to create an abstract class and use it. For this example, we have
used a well-known polymorphism example of shape class. The Shape class contains an abstract
method calculateArea() which is abstract. Class Circle extends from abstract Shape class,
therefore to become concrete class it must provide the definition of calculateArea() method.

Follow the steps given below to create a class.

1. Open Notepad and type the following code.

public abstract class Shape{


public abstract void calculateArea();
}

2. Save the file as Shape.java.


3. Open new Notepad and type the following code

public class Circle extends Shape {


private int x, y;
private int radius;
public Circle() {
x = 5;
y = 5;
radius = 10;
}
// providing definition of abstract method
public void calculateArea () {
double area = 3.14 * (radius * radius);
System.out.println(“Area: ” + area);
}
}

4. Save the file by the name of Circle.java. This is the class which has implemented the abstract
class.

The Test class contains main method. Inside main, a reference s Shape class is created. This
reference can point to Circle asdiscussed earlier. By using reference, method calculateArea()
of circle class can be invoked.

5. Open the notepad again and type the following code and save the file by the name of
Test.java.

Department of Computer Science, Page 41


C.U.S.T.
Lab 4: Abstract Classes and Interfaces

public class Test {


public static void main(String args[]){
//can only create references of A.C.
Shape s = null;
//Shape s1 = new Shape(); //cannot instantiate
//abstract class reference can point to concrete subclass
s = new Circle();
s.calculateArea();
}
}//end of class

6. Compile all the classes and run the test class to test the program.The compilation and
execution of the above program is shown in figure 2.

Figure 2: Execution of program containing abstract class

6.3.2 Implementing Interfaces

Interface is implemented in a class that declares that it implements theparticular interface or


interfaces. It is important to understand thatall constants that were defined in the interface are
available directly in the class. It is same as the inheritance concept.Relationship between a class
and interface is equivalent to “is a” relationship exists in inheritance. (Discussed in OOP
manual)

To implement the interface, you will have to follow the following steps.

1. Open Notepad and type the following code, finally save the file by the name of
PrintableInterface.java

public interface PrintableInterface{


public void print();
}

2. Class AcpStudent implement that interface. AcpStudent class has to provide the definition
of print method or we are unable to compile the code successfully.Open another Notepad to
type the following code.

public class AcpStudent{

Department of Computer Science, Page 42


C.U.S.T.
Lab 4: Abstract Classes and Interfaces

private String regNo;


private String Name;

public String toString () {


return "name:"+name +" registration number:"+ regNo;
}
public void print() {
System.out.println("Name:" +name+" registration number:"+ regNo;
}

3. Finally write a test class as written for abstract class and run the program.

7. Practice Tasks

This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the
following folder:
\\dataserver\assignments$\Advanced Computer Programming\Lab2

7.1 Practice Task 1 [Expected time = 10mins]

Create an interface named as Shape, which will have a method printShape and implement this
method in two different classes i.e. Circle and Cube. Call the print shape of circle and cube
using shape reference.

7.2 Practice Task 2 [Expected time = 15mins]

Create an interface of car rentals offering multiple companies that rents cars. It can be
implemented by multiple companies and offer services to rent cars of customer’s choice.

7.3 Practice Task 3 [Expected time = 15mins]

Create an interface named as RemoteControl which will have below mentioned methods
public boolean powerOnOff();
public int volumeUp(int increment);
public int volumeDown(int decrement);
public void mute();
public int setChannel(int channel);
public int channelUp();
public int channelDown();
and implement these methods in different classes i.e. TV and DVD and demonstrate it as a
Polymorphism example

Department of Computer Science, Page 43


C.U.S.T.
Lab 4: Abstract Classes and Interfaces

7.4 Practice Task 4 [Expected time = 10mins]

Create an interface which is of networking Franchise, it further has multiple types as of zong,
ufone, telenor, warid etc. It offers multiple services offered at franchises. Package offers, it can
further contains sms packages, call packages, internet packages etc.

7.5 Practice Task 5 [Expected time = 10mins]

Part - 1: Search at least three interfaces (other than example given below) in JAVA docs at
http://docs.oracle.com/javase/7/docs/api/ and list its all methods like this: EventListener and its
method is handleEvent,
Part - 2: Then make a class that implements any of the interfaces you found in Q 5 Part -1, try to
execute program without implementing any of the interface’s method and list down the error you
receive.

7.6 Out comes

After completing this lab, student will be able to understand the use of abstract class and
interface.

7.7 Testing

This section provides you the test cases to test the working of your program. If you get the
desired mentioned outputs for the given set of inputs then your program is right.

Test Cases for Practice Task-1

Sample Input Sample Output


The Name of the shape is : Circle
The Name of the shape is : Cube

Test Cases for Practice Task-3

Sample Input Sample Output


1 Device turned On
4 Sound Muted
7 Channel Changed

The test cases for other tasks will be provided by your lab instructor when you will finish your
tasks.

8. Evaluation Task (Unseen) [Expected time = 55mins for two tasks]

The lab instructor will give you unseen task depending upon the progress of the class.

Department of Computer Science, Page 44


C.U.S.T.
Lab 4: Abstract Classes and Interfaces

9. Evaluation criteria

The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).

Table 3: Evaluation of the Lab


Sr. No. Task No Description Marks
1 4 Problem Modeling 20
2 6 Procedures and Tools 10
3 7 Practice tasks and Testing 35
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

10. Further Reading

This section provides the references to further polish your skills.

10.1 Books

Text Book:
 Java: How to Program by Paul J. Deitel, Harvey M. Deitel. Eighth Edition
 Java Beginners Guide:
http://www.oracle.com/events/global/en/java-outreach/resources/java-a-beginners-
guide-1720064.pdf

10.2 Slides

The slides and reading material can be accessed from the folder of the class instructor available
at \\dataserver\jinnah$\

Department of Computer Science, Page 45


C.U.S.T.

You might also like