0% found this document useful (0 votes)
160 views

Lab 2 Abstract Classes and Interfaces

This document provides instructions for a lab on abstract classes and interfaces in Java. It includes an introduction to key concepts like abstract classes, abstract methods, interfaces, and extending interfaces. The objective is for students to get hands-on practice implementing abstract classes and interfaces. The procedure explains how to set up Java Development Kit 1.7 and compile/run programs. Students will complete practice tasks to demonstrate abstract classes and interfaces.

Uploaded by

david jhon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
160 views

Lab 2 Abstract Classes and Interfaces

This document provides instructions for a lab on abstract classes and interfaces in Java. It includes an introduction to key concepts like abstract classes, abstract methods, interfaces, and extending interfaces. The objective is for students to get hands-on practice implementing abstract classes and interfaces. The procedure explains how to set up Java Development Kit 1.7 and compile/run programs. Students will complete practice tasks to demonstrate abstract classes and interfaces.

Uploaded by

david jhon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Lab Manual for Advance Computer Programming

Lab-02
Abstract classes and Interfaces
Lab 2: Abstract Classes and Interfaces

Table of Contents
1. Introduction 15

2. Objective of the experiment 16

3. Concept Map 16
3.1. Super class 16
3.2. Encapsulation 16
3.3. Abstract class 16
3.4. Abstract method 17
3.5. Interface 17
3.6. Extending Interfaces 18

4. Procedure& Tools 18
4.1. Tools 18
4.2. Setting-up JDK 1.7 18
4.2.1. Compile a Program 18
4.2.2. Run a Program 19
4.3. Walkthrough Task 19
4.3.1. Implementing Abstract Class 19
4.3.2. Implementing Interfaces 20

5. Practice Tasks 21
5.1. Practice Task 1 21
5.2. Practice Task 2 22
5.3. Practice Task 3 22
5.4. Practice Task 4 22
5.5. Practice Task 5 22
5.6. Out comes 22
5.7. Testing 22

6. Further Reading 23
6.1. Books 23
6.2. Slides 23

Page 14
Lab 2: Abstract Classes and Interfaces

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

Page 15
Lab 2: Abstract Classes and Interfaces

interfaces as we like but any class can extend only one class. Multiple inheritance that was
supported by C++ has been removed by Java.

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

3. Concept Map

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

3.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.

3.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.

3.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.

Page 16
Lab 2: Abstract Classes and Interfaces

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 details i.e.
implementation of undefined methods.

3.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.

3.5. Interface

Similar to Abstract class, interfaces imposes 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 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.

Page 17
Lab 2: Abstract Classes and Interfaces

public interface TestInterface {


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

abstract public class interfaceExample implements TestInterface {


public void myMethod1(){
}
}

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

4. Procedure& Tools

4.1. Tools

Java Development Kit (JDK) 1.7

4.2. Setting-up JDK 1.7

Refer to Lab 1 sec 6.2.

4.2.1. Compile a Program

Use the following command to compile the program.

javac Interface.java

After the execution of the above statement byte code 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.

Page 18
Lab 2: Abstract Classes and Interfaces

4.2.2. Run a Program

After successfully completing the section 6.2.1, the only thing left is to execute the byte
code 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.

4.3. Walkthrough Task

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

4.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 belowto 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

Page 19
Lab 2: Abstract Classes and Interfaces

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.

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

4.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.

Page 20
Lab 2: Abstract Classes and Interfaces

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{


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.

5. Practice Tasks

This section will provide more practice exercises related to development. You need to finish the
tasks in the required time. When you finish them, put these tasks into the
https://moellim.riphah.edu.pk/.

5.1. Practice Task 1

Create a class Glass with attributes opacity and thickness. The class contains an abstract
method show. Extend a class WindowGlass from Glass and add two new attributes width
and height. Override the show method that displays all the attributes. Create a class
CarWindowGlass that extends WindowGlass and also define its own show method that
displays all the attributes.

Page 21
Lab 2: Abstract Classes and Interfaces

5.2. Practice Task 2

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.

5.3. Practice Task 3

Create an interface VehicleFunctions with methods


 void switchOn();
 void drive();
 void switchOff();
 void turnOnLights();
 void turnOffLights();

Create an abstract class Vehicle with attributes name, model, brand and number_of_wheels.
Create an abstract method display() .
Create two concrete classes Car & Bike that extends Vehicle and implements
VehicleFunctions.

5.4. Practice Task 4

Search or create three interfaces in the java and make a test program to check these
interfaces.

5.5. Practice Task 5

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.

5.6. Out comes

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

5.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.

Page 22
Lab 2: Abstract Classes and Interfaces

Test Cases for Practice Task-1

Sample Input Sample Output


Features :
-Opacity : 10.0
-Thickness : 1.5
-Width : 10.0
-Height : 10.0
-Tint percent : 7

Test Cases for Practice Task-3

Sample Input Sample Output


1 Name : Honda CD 125
Model : CD-125
Brand : Honda
Wheels : 2
Racer : false
Bike started
Bike is being driven
Bike lights are turned on
Bike lights are turned off
Bike switched off

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

6. Further Reading

This section provides the references to further polish your skills.

6.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

6.2. Slides

The slides and reading material can be accessed from the folder of the class instructor
available at https://moellim.riphah.edu.pk/

Page 23

You might also like