92
1 Course: CSC241- Object Oriented Programming Department of Computer Learning Procedure 1) StageJ(Journey inside-out the concept) 2) Stagea 1 (Apply the learned) 3) Stagev(Verify the accuracy) 4) Stagea 2 (Assess your work)

Course: CSC241- Object Oriented Programmingmnk.muhammadiyah.info/Lab Manuals/ver 2/OOP Lab Manual.docx  · Web viewThis is the way in which traditional programming works, but now

Embed Size (px)

Citation preview

1

Course: CSC241- Object Oriented Programming

Department of Computer Science

Learning Procedure

1) StageJ(Journey inside-out the concept)

2) Stagea1(Apply the learned)

3) Stagev(Verify the accuracy)

4) Stagea2(Assess your work)

Table of Contents

Lab # Topics Covered Page #

Lab # 01

Functions and pointers recap 03

Lab # 02

Introduction to Classesand Objects 09

Lab # 03

OOP Design: Decomposition into Objects (Association) 14 OOP Design:Decomposition into Objects (Aggregation,

Composition);

Lab # 04

Access Specifiers, Constructorsand Destructors 21Constructor Overloading andCopyConstructors

Lab # 05

Passingarguments and returning valuesfrommethods. 29

Lab # 06

Lab Sessional 1

Lab # 07

Encapsulation: Privacy and Visibility of Class Members, package access 35

Lab # 08

Static data and methods 39

Lab # 09

Inheritance 46

Lab # 10

Method overloading and overriding 51

Lab # 11

Interfaces, their usage, and abstract classes 57

Lab # 12

Lab Sessional 2

Lab # 13

Polymorphism 63

Lab # 14

Exception handling 67File handling

Lab # 15

Swing GUI controls 72

Terminal Examination

2

Statement Purpose:This lab is a refresher course on the use of functions, pointers and building logic.

Activity Outcomes:After completing this lab the student should be able to:

Understand the purpose/ advantage of creating a function. Understand the difference between a function definition and prototype. Understand the difference between a parameter and an argument. Understand how a function is created and called. Understand how values are passed by value and by reference to a function. Returning the values

thereafter. Use pointers and manipulate variables using pointers. Use an array with pointers in a function.

Instructor Note:Lecture 1,2

Text book:

AbsoluteJava, Savitch,W.&Mock, K., 5th Edition(2012), Pearson

3

LAB # 01

1) StageJ(Journey)

Introduction

We have already seen how variables are memory cells that we can access by an identifier. But these variables are stored in concrete places of the computer memory. For our programs, the computer memory is only a succession of 1 byte cells (the minimum size for a datum), each one with a unique address. A good simile for the computer memory can be a street in a city. On a street all houses are consecutively numbered with a unique identifier so if we talk about 27th of Sesame Street we will be able to find that place without trouble, since there must be only one house with that number and, in addition, we know that the house will be between houses 26 and 28. In the same way in which houses in a street are numbered, the operating system organizes the memory with unique and consecutive numbers, so if we talk about location 1776 in the memory, we know that there is only one location with that address and also that is between addresses 1775 and 1777.

2) Stage a1 (apply)

a) Reusability/ Modularity ofCode

Computer programmers have always devised mechanisms through which they can make their code more understandable and then reusable. In this regard functions offer a very popular and easy mechanism of introducing the above goals. Function handling operates on the concept of provision of service/ functionality. We can call the services of a function by providing the required data and in result getting the promised service from the function.

Reusability of code means devising methods through which you can use code again and again without having to copy-paste in the source file. Modularity of code means dividing the code into small, manageable and easy to understand segments.

b) Function Prototype and FunctionDefinition

The creation of a function is based on two similar yet distinct statements called a function definition and function prototype.

A function prototype explains only how a function will be called and what data type it will return. A function definition on the other hand matches the function prototype and also includes a function body.

For example the following is the function prototype of a function that finds the sum of two integers passed to it:

void addtwo (int, int);

The following is the function definition of the above defined function:

void addtwo (int a, int b)

4

{

int c=a+b;

cout<<”The sum is ”<<c;

}

c) Function Arguments andParametersThere are two types of variables a function is related with; namely function arguments and function parameters. Function arguments are those variables that are provided to a function. These variables are passed whenever a function is called.Function parameters are those variables that are created and initialized when parameters are passed to a function. The scope of a function parameter is always within the body of the function. It should be pointed out here that any variablethatiscreatedinafunctionbodyhasalocalscopeandcannotbeaccessedoutsidethefunctionbody.The data type of arguments must match the parameters of a function.

In the following example, variables a and b are parameters of the function addtwo( ).

void addtwo (int a, int b);

{

int c=a+b;

cout<<c;

}

Now suppose we are calling the same function from within the main().void main( )

{

int x=3, y=4;

addtwo(3,4);

}

d) Returning a Value from aFunction

To increase the practical use of functions, a programmer may want the result of a function to be given back after processing. This process is called returning a value from a function. It is important to remember that functions can only return a single value (of any data type). If a function will not return a value then it is necessary to write void before the function name in the prototype and the definition. It is not necessary for a function to return a value.

For example the following function does not return a value hence the void keyword is used

void addtwo (int a, int b);

5

{

int c=a+b;

cout<<c;

}

The following function returns an integer value hence the keyword int is used.

intaddtwo (int a, int b);

{

int c=a+b; return

(c);

}

The value being returned can be displayed by using the following statement from where the function is being called.

cout<<addtwo(x, y);

e) Pass by Value and Pass byReference

All the functions we have discussed until now are pass by value. Pass by value is an argument passing technique in which the function receives a parameter and works with a copy of the value being provided. This means if a change is made to the parameter value then still no change will not be reflected in the argument.

On the other hand pass by reference is an argument passing technique in which the function works with the exact variable that is being passed as an argument. This means that even the smallest change in a parameter will be exactly reflected in the arguments. This further implies that the arguments and the parameters are tightly coupled.

6

b

Pointers

Pointers are special kind of variables that are allowed to hold the address of another variable. Because of their pointing ability pointers are considered very powerful in C++. Pointers can hold the address of another variable and this is called referencing the memory location. When we attempt to extract values from a memory location then this is called dereferencing a pointer.

Figure 1: The working of a pointer (image courtesy of Wikipedia)

In the figure provided above there is a pointer variable called “a”. This variable is pointing to the memory address of variable b. The memory address of variable b is 1008. In this diagram you will also note that the pointer “a” has its own memory address. This is a very important fact because pointers themselves also require a space in memory. When we write a code on our compilers remember that every computer has its own memory and the availability of memory space. Our compilers take the help of a memory manager and allocate space in a memory slot that is available to the system. This means every time we run the code we

7

may get a different memory allocation.Consider the code provided below:

Figure 2: The various operations that can be performed with a pointer. Output is also provided. Memory addresses may be different depending on the hardware environment

In the code above first a simple integer variable is created. Then an integer pointer is created because we intend to point to an integer variable. The pointer is then given the address of variable x by using the address operator. Then we use the dereference operator (*) that directs us to the memory location where the pointer is pointing to.

3) Stage v (verify)

Home Activities:

Activity 1: Compile and run sample program 1 and sample program 2 given on page 3 of the handout.Activity 2:Write a program to initialize a float array of size 10 with values : 0.0 , 1.1 , 2.2 … 9.9 using Pointers.Activity 3:Write a program to input 5 numbers into an array and to calculate their sum and average using only Pointers to address array elements.

4) Stage a2 (assess)

Assignment:

Write a program to input 5 numbers into an array and to calculate their sum and average using only Pointers to address array elements.

8

Statement Purpose:This lab gives the introduction and detailed practical concepts of classes and objects.

Activity Outcomes:

After completing this lab the student should be able to: Clearly understand the purpose and benefits that OOP has tooffer. Understand the concept of a class andobjects. Develop a basic class with fundamental datamembers. Develop a basic class with a number of memberfunctions. Use a constant memberfunction. Separate the implementation section of afunction. Use the class objects and member functions to provide and extract data from anobject. Experiment with classes andobjects.

Instructor Note:Lecture 3

Text book:

AbsoluteJava, Savitch,W.&Mock, K., 5th Edition(2012), Pearson

9

LAB # 02

1) StageJ(Journey)

Introduction

The programming that you have understood in your computer programming course, allows you to design a program by assembling a sequence of instructions. This is the way in which traditional programming works, but now there is clear paradigm shift towards an object based approach. The new object oriented approach allows you to model your program in a way in which objects, their relationships and the functions that they operate are clearly visible to the programmer.Perhaps the greatest advantage of this approach is that it gives an extended modular concept in which the interface is made public while the implementation details are kept hidden. This allows the program to grow in size without becoming too cumbersome. Previously, when a program grew beyond a certain size it became almost impossible to understand and extend especially when the programmer had forgotten the minor concepts constructing the program. Here, it should be understood and acknowledged that programs are not disposable entities they have a life beyond what is normally expected. Hence designing a program that can be easily extended, modified and interfaced with other systems is a very important characteristic of any well written program.This lab has been designed to give in-depth knowledge of how to make classes, objects and their interrelations. The concept map provides all the crucial details that are required for the completion of this lab.

2) Stage a1 (apply)

Object

In OOP an object is a very much like a real world object. An object can be defined as a collection of state and behaviour. For example, consider the example of a cat. A cat is has both a state and behaviour. The state of a cat is its attributes namely colour, breed, gender, age, weight, height, etc. Whereas the behaviour of a cat is its sound, eating, sleeping, yawning, walk, etc. Hence a cat can be completely identified by its unique characteristics and behaviours.

In programming an object is a collection of variables and functions that together have a unique purpose of identifying a distinctive entity.

DataMembers

Again referring to the concept of an object and the example of a cat. The cat had a number of characteristics or attributes that can be used to identify a cat. In programming these attributes can be programmed by using regular variables that are called data members. A class can be composed of a number of data members of various types. The data members of a class are private by default i.e. they are not directly accessible outside the class.

Here it is important to point out that often people casually refer to these as variables, which is a wrong terminology. These should only be called data members or class variables.

MemberFunctions

10

using namespace std;class myclass{intdatamember;intmemberfun(int);

// Functionprototype};intmyclass :: memberfun(intx)// Note the scope resolutionoperator{...// Functionbody}void main( ){}

Again referring to the concept of an object and the example of a cat. The cat had a number of behaviours or things that a cat does. In programming these behaviours can be programmed by using functions that are called member functions. A class can be composed of a number of member functions of various types. Overloading of member functions is also permitted in C++. The implementation section of member functions can be separated whereby the body of the function is created outside the class but the function prototype has to exist in the body of the class. The implementation section is separated by writing the return type followed by class name. This is further followed by scope resolution operator :: and then the remaining function definition.

Constant MemberFunctionsA constant member function is just like a conventional function except it is a read only function. This means that the function cannot modify anything related to the object. But the member function can still perform all reading activities related to the object. Such type of functions are generally created when the programmer wishes to only read/ display the data members on the screen. Given below is the syntax for creating these constant member functions.

void addtwo ( ) const //Note the keyword const

{

cout<<”The sum is= ”<<s;

}

Class

A class is a collection of data members and member functions. A class is used to define an abstract data type. This abstract data type is used in the construction of an object which is used to access all the data members and member functions. A class has to be created before it can be used. Provided below are the syntax for creating a class.

Activity:

Write a program that creates a class called cylinder. The data members of the class are radius and height of the cylinder is provided. Write two functions that set the respective values and then write a single constant function that will read the values.

11

WritingCode

In the source file created in the project “cylinder” write the following C++ code:

Figure 1: Class for creating a cylinder with its relevant data members

CompilationAfter writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings that are present in your code.

Executing theProgram

A sample output after running the program is shown below. Also run the code with other possible inputs.

12

3) Stage v (verify)

Home Activities:

Activity1Write a C++ program that creates a class called laptop. The data members of the class are brand (string), model (string), serial (int), colour (string), price (float), processor speed (float), RAM (int), screen size(float).Create member function that will set the individual values. Since the RAM can be upgraded therefore create a function that allows you to upgrade the RAM only. In the end, create a function that will display all the data members.

Activity2Write a class called rectangle. Your task is to store the length and width of the rectangle. Write a member function called increment that will add 1 to the value of length and width. Also write a function that will compute the area of the rectangle. Finally write a constant function that will display the length, width and area of the rectangle.Demonstrate the use of the object in the main function. Make sure that the function names are meaningful and self descriptive.

Activity3Write a program that creates a class called number. Your class will have two data members namely num (float) and result (int). To find the factorial of the entered number you will need to design three functions as follows:

Function to determine if a number is a whole number ornot Function to determine if the number is positive ornot Function to find the actualfactorial Function to display the number and itsfactorial

Remember that to find the factorial the number must of positive and a whole number. So if any of these conditions are not met then you cannot determine the factorial.

4) Stage a2 (assess)

The lab instructor will assign an unseen task depending upon the progress of the students.

13

Statement Purpose:This lab gives the concept of Association, Composition, and Aggregation in Object Oriented Programming.

Activity Outcomes:

In this lab we will discuss Association in Java. Association establishes relationship between two classes through their objects. The relationship can be one to one, one to many, many to one and many to many. Inheritance establishes IS-A relation, but association give us HAS-A relationship.

Composition and Aggregation are also implemented in detail.

Instructor Note:Lecture 4,5

Text book:

AbsoluteJava, Savitch,W.&Mock, K., 5th Edition(2012), Pearson

14

LAB # 03

1) StageJ(Journey)

Introduction

Aggregation is a relationship between two classes that is best described as a "has-a" and "whole/part" relationship. The aggregate class contains a reference to another class and is said to have ownership of that class. Each class referenced is considered to be part-of the aggregate class. For example; a computer has components keyboard monitor, mouse and processor box. The relationship between computer and its component is aggregation.

In this lab we will also discuss Association in Java. Association establish relationship between two classes through their objects. The relationship can be one to one, One to many, many to one and many to many. Inheritance establishes IS-A relation, but association give us HAS-A relationship.

2) Stage a1 (apply)

Example: public Class A { public int a; } public Class B { public int b; A aObj; B() { this.b=0; aObj.a=0; } } class CarClass{ String carName; double carSpeed; intcarId; CarClass(String name, double speed, int Id) { this.carName=name; this.carSpeed=speed; this.carId=Id; } } class Driver{ String driverName; intdriverAge; Driver(String name, int age){ this.driverName=name; this.driverAge=age; }

15

} class TransportCompany{ public static void main(String args[]) {

16

CarClassobj= new CarClass("Ford", 180.15, 9988); Driver obj2 = new Driver("Andy", 45); System.out.println(obj2.driverName+" is a driver of car Id: "+obj.carId); } }

In the above example, there is a one to one relationship (Association) between two classes: Car and Driver. Both the classes represent two separate entities.

Association commonly has two forms 1. Aggregation 2. Composition

1. Aggregation: is a special form of association which is a unidirectional one way relationship between classes, for e.g. Wallet and Money classes. Wallet has Money but money doesn’t need to have Wallet necessarily so it's a one directional relationship. In this relationship both the entries can survive if other one ends. In our example if Wallet class is not present, it does not mean that the Money class cannot exist.

Aggregation Example: Consider two classes Student class and Address class. each student must have an address so the relationship between student and address is a Has-A relationship. But if you consider its vice versa then it would not make sense as an Address doesn’t need to have a Student necessarily. Below example shows this theoretical explanation in a sample java program.

class Address { intstreetNum; String city; String state; String country; Address(int street, String c, String st, String coun) { this.streetNum=street; this.city =c; this.state = st; this.country = coun; } } class StudentClass{ introllNum; String studentName; Address studentAddr;

17

StudentClass(int roll, String name, Address addr){ this.rollNum=roll; this.studentName=name; this.studentAddr = addr; } public static void main(String args[]){ Address ad = new Address(55, "Agra", "UP", "India"); StudentClassobj = new StudentClass(123, "Chaitanya", ad); System.out.println(obj.rollNum); System.out.println(obj.studentName); System.out.println(obj.studentAddr.streetNum); System.out.println(obj.studentAddr.city); System.out.println(obj.studentAddr.state); System.out.println(obj.studentAddr.country); } } class Car { private Engine engine; void setEngine(Engine engine) { this.engine = engine; } void move() { if (engine != null) engine.work(); } }

In above example engine does not created when Car object created from Main. it come to existence using function setEngine(Engine engine). So engine is optional component for car.

2. Composition: is a restricted form of Aggregation in which two entities (or you can say classes) are highly dependent on each other. For e.g. Human and Heart. A human needs heart to live and a heart needs a Human body to survive. In other words when the classes are dependent on each other and their life span are same (if one dies then another one too) then its a composition. Heart class has no sense if Human class is not present.

Composition Example:

class Car { private final Engine engine; Car() { engine = new Engine();} void move() { engine.work(); } }

18

In the case of composition, the Engine is completely encapsulated by the Car. There is no way for the outside world to get a reference to the Engine. The Engine lives and dies with the car. With aggregation, the Car also performs its functions through an Engine, but the Engine is not always an internal part of the Car. Engines may be swapped, or even completely removed. Not only that, but the outside world can still have a reference to the Engine, and tinker with it regardless of whether it's in the Car.3) Stage v (verify)

Home Activities:

Activity 1:

A famous hotel in city has only three rooms. Room can exist without hotel. but hotel cannot exist without rooms. so clearly, it is unidirectional relation. Implement this scenario. Room class must have its attributes like hourly Rate, its dimensions, number of persons that can stay in that room, while Hotel class contain its name only and three rooms. Dimension is class that has only two data members width and height. Room and Dimension has one to one relation. From Main, create hotel by setting its name, and assign three rooms to hotel. When room is created initialize default dimensions (with:10, length:10) to room. As every room must have dimension. So it is example of composition.

Activity 2: Define a class Priority_Queue that represents a bounded priority queue of nodes. To represent a node you must define a class Node having member variables Data (description of node,type string) and a Priority_No. In Priority_Queue class, provide following two methods. Enqueue: that inserts a node in the queue at appropriate position, based on its Priority_No, if queue is not full. Dequeue: that displays and removes a node from front of the queue, if queue is not empty.

Activity 3: Create a class Employee, the member data should include Employee number (type integer), Name of employee [to be allocated dynamically] and Salary (comprising of three float variables; Gross pay, Deductions and Net pay). Also include date of joining of employee. The date should comprise of three integers representing day, month and year. You need to define separate classes for Date and Salary. Include necessary constructors, destructors and member functions to enter and display the data in each class.

Activity 4: Define a class Database that uses a dynamic array of Employee’s objects to stores the record of employees. Also provide following methods in Database class. Add: To add a new employee Delete: To remove an employee’s record Search: To search a record by employee number.

Activity 5:

19

Write a driver program that creates an object of Database class and calls its functions according to user requirement.

4) Stage a2 (assess)Activity 1: Define a class Database that uses a dynamic array of Employee’s objects to stores the record of employees. Also provide following methods in Database class. Add: To add a new employee Delete: To remove an employee’s record Search: To search a record by employee number.

Activity 2: Write a driver program that creates an object of Database class and calls its functions according to user requirement.

20

Statement Purpose:This lab gives the concept of Access Specifiers, Constructorsand Destructors. It also emphasizes on the method of Constructor Overloading andCopyConstructors.

Activity Outcomes:

After completing this lab the student should be able to: Clearly understand the purpose and importance of accessspecifiers. Develop a class by correctly using/ enforcing accessspecifiers. Differentiate between the public and private accessspecifier. Understand the importance ofconstructors. Understand the importance ofdestructors. Use a basicconstructor. Use a basicdestructor. Develop a constructor and then overloadit Understand the difference between a parameterized constructor and non

parameterizedconstructor Develop a copy constructor and facilitate the copying of data from one object to theother.

Instructor Note:Lecture 6,7

Text book:

AbsoluteJava, Savitch,W.&Mock, K., 5th Edition(2012), Pearson

21

LAB # 04

1) StageJ(Journey)

Introduction

This lab is designed to teach three very basic yet essential concepts of OOP namely access specifiers, constructor and destructors. Access specifiers provide a technique through which we can restrict access to data members and member functions. After enforcing access it is important to reduce our reliance on too many member functions. Constructors offer a very attractive and easy to implement technique through which we can take steps call procedures whenever an object is created. The use of constructors is preferred over the use of member functions because constructors are called automatically and hence they can invoke further functions whereas simple member functions have to be called sequentially and explicitly one by one every time an object iscreated.Similarly this lab also focuses on the use of destructors that are called whenever an object goes out of scope. In this the lab the students will be familiarized with the use of access specifiers, constructors and destructors.

Constructors are special functions that are automatically called when an object is created. This lab is geared towards an extended use of constructors through overloading. Another flavour of constructors is the copy constructor which creates an object by using a previously implemented object. This can be accomplished through the use of a copy constructor.

2) Stage a1 (apply)

a. Access Specifiers – Public and PrivateAccess

Access specifier also known as access modifier provides a technique for enforcing access control to class members (data members and member functions). The use of access specifiers enforces encapsulation and data hiding. C++ provides three access specifiers i.e. public, private and protected. In this lab we will only cover the public and the private access specifier. The protected specifier is left for future discussions.

The public access specifier is the one that provides unrestricted access to the class members. While the private access specifier provides a very strict/ restricted access to class members. All the class members that are written under the public access can be accessed both inside and outside the class without any restriction. On the other hand all the class members written as private are accessible inside the class but are not accessible outside the class. The best and most common way of accessing private data members is through the use of a publicfunctions.

22

using namespace std;class myclass{private:intdatamember; public:intmemberfun(int);};

//Private datamember

// public member function

intmyclass :: memberfun (int x) because its prototype is public{datamember=x;}

// This function is still public

void main( ){myclassobj; myclass::datamember=10; obj.memberfun(10);}

//Syntax Error: privatemember

When we are discussing access specifiers it must be pointed out that by default classes are private whereas structures are public. Hence if you do not write private then your listed class members are considered private in a class.

The correct convention for the use of access specifiers is that data members are kept private whereas functions are kept public. Hence you are providing a public interface for accessing restricted items in a class.

ConstructorsA constructor is a function that is automatically called when an object is created. This function can exhibit the regular behaviour of any function except that it cannot return a value. The reason why constructors are needed is that unlike regular functions which need to deliberately called, a constructor will be automatically called when an object is created. Every constructor has a body from where we can call regular member functions.

23

using namespacestd;class myclass{private:intdatamember; public:myclass( );{

//Private datamember

//Class constructor

cout<<”Hello you have called the classconstructor”;}};

void main( ){myclassobj;}

A very important question which is often asked is that how does the compiler know that the constructor function needs to be called automatically? The answer is very simple. A constructor is a function that has the same name as the class. Whenever an object is created the compiler searches for a function having the same name as the class i.e. the constructor. Given below is a sample code that shows the class constructor. Generally the constructor is defined as public. Also the constructor can be overloaded like a regular member function. An important point regarding a constructor is that it cannot return a value. In fact writing the keyword void is strictly prohibited.

DestructorsConstructors are designed to help initialize/ create an object. Destructors on the other hand do exactly the opposite. Destructors are called whenever an object goes out of scope. When this happens it is necessary to perform cleanup procedures especially when you have used dynamic memory or you have been working with pointers in your code. The destructor function can be used to free up memory that you have allocated or dereference pointers that were referenced. The rules for a destructor are as follows:

They have the same name as the class just simply preceded by a tilde(~) They can take noarguments They cannot return anything, not evenvoid.

FunctionOverloading

Function overloading is an advanced concept in modern languages where two function can have the same name. The question that arises here is that how does a compiler know which function to call. The simple answer is that the function calling is determined based on the type of parameters/ the number of parameters being passed/ order of parameters being passed. Hence two function can have the same name but there must be a difference in the number of parameters, type of parameters or the order of parameters. For example

24

in the function prototypes below the function fun( ) has been overloaded and its different flavours are presented.

int fun (int,

float, float); int

fun (int, float);

int fun (float, float, int);

It is important to highlight here that if two functions have a different return type then it does not mean that they are overloaded. For a function to be overloaded it is necessary for the function to exhibit changes in the parameters.

Constructor Overloading – Parameterized and NullaryConstructorsConstructors are designed to help initialize/ create an object. A constructor is a special function that is automatically called upon the creation of an object. The important fact that needs to be communicated is that constructors do not have a return type. In fact using the keyword void is also prohibited.Constructors are of two types namely: Nullary Constructors / Parameterless Constructors – Those constructors that do not

need a parameter to be called. Parameterized Constructors – Those constructors that require parameters for

theircallingInside a class C++ allows us to overload a constructor just like any other function. This means in the same class you can have a nullary constructor alongside a parameterized constructor. Consider the code belowfor further reference.

25

class example{private:int one; int two;float three; public:example( ){...} //Nullaryconstructor

example (int on, inttw, float th)parameterized->1{...}

//OverloadedConstructor:

example (int on, float th, inttw): Parameterized ->2{...}};intmain(){

//Another overloadedConstructor

exampleobj;//Creation through nullaryconstruexample obj2(1,2,3.3);//Creation through firstparameterizedconstruexample obj3(1,3.3,2);//Creation through Secondparameterizedconstrureturn0;

}CopyConstructors

Copy constructors provide a function through which you can create a new object from an existing already created object. This feature is commonly used in simple programming and hence its need can arise at any time when working with objects. C++ provides a default copy constructor that will assist in the copying of simple objects. For example objects that do not use pointers or arrays. Although the default copy constructor will copy any type of object but it is strongly recommended that the copy constructor be used only for objects that have non pointer data members. The default copy constructor performs a member by member copy i.e. the copy constructor creates an exact copy where data members are copied one by one to the new object. Always remember that in copy constructors the original object is maintained in its original state and the copy changes are only exhibited in the newly created object. In this lab we will just restrict ourself to the use of the default copyconstructor.The default copy constructor can be explicitly called as follows:

clssobj2(obj1); // Functioncallingnotationclss obj2=obj1;

//Assignment statementnotation

Both statements create an object of the clss class. Of course any of the above statements can be used for copying an object into another object.

26

Caution: The copy constructor is always called at the time of creating a new object. If at any time after the creation of objects you copy contents of one object to the other then the copy constructor is not called. We will discuss more on this in future lectures.

3) Stage v (verify)

Home Activities:

Activity 1:

Write a C++ program that creates a program for a new ice cream vendor called LeCream. The management of LeCream has decided that they are going to sell their ice cream in 7 different flavours namely chocolate, vanilla, strawberry, mango, tutti fruit, almond crunch and coffee. Carefully design the program by observing the following rules.

LeCream is charging Rs 100 for two scoops and Rs 150 for three scoops. Hence you will need a function to determine the number of scoops and based on that the price. If a user enters more than three scoops your program should display invalid input and it shouldexit.

LeCream allows its customers to purchase a vanilla wafer with their ice cream. If the customer wants to purchase the wafer he will have to pay an additional Rs 10. This amount should be added to the total amount payable by theuser.

If the customer asks for chocolate flavour then he will have to pay an additional amount i.e. Rs 120 for two scoops and Rs 180 for three scopes. Design a function that will be called if the customer chooses flavoured icecream.

The program should show a menu that asks the customer for his requirements and then displays the final payable amount with full details about the flavour, number of scoops andwafer

In the end create a class destructor that displays a thank you message to theuser.

Design your program using sound OOP practices. Carefully determine the data members, member functions, access specifiers, activities to be performed in the constructor. Make sure that you use good naming conventions in your code. A good design can earn you higher marks.

Activity 2:

VISION is a world leader in manufacturing LCD Televisions. The company has decided that it will allow its customers to give the dimensions of the TV (in length and width). Once the length and width are ordered the company will manufacture the TV according to your requirements. In this regard they want you to create a program that will assist them. Carefully read all the instructions and follow the requirements.

Create a class calledvisionCreate three constructors asfollows:- A nullary constructor that calls the setlength( ) and setwidth( )function.- A parameterized constructor that will receive the length and width asintegers- A parameterized constructor that will receive the length and width infloat

By using a special function calculate the area of theTVCreate a function to calculate the price of the TV by multiplying the area with Rs.65.Create a display( ) function to show the details of the purchasedTV.

In the main you will construct three objects that demonstrate the use of the three constructors. After calling the constructor it will take over and will handover control to the area function, and then the price calculation function.Remember that the user should not have access to modifying the price.

27

Determine the access specifiers, data members and member functions. Also note that each constructor can / will have a distinct functionality in its body. Hence do not try to copy code from one constructor to the other. Focus on the design clarity and quality of yourcode.

4) Stage a2 (assess)

Activity 1:Once you have completed the above task you are also required to use the default copy constructor to show that values have been copied to the new created object. Use the display( ) function to show the individual objects.

OutcomesAfter completing this lab, students will be able to construct a class object by using parameterized constructors. The students will also be familiar with the use of a constructor and destructor.

28

Statement Purpose:This lab gives the concept of Passingarguments and returning valuesfrommethods.

Activity Outcomes:

After completing this lab the student should be able to: Syntax difference java and c++ Objects as Function Arguments How to take input from user in java (import scanner class)

Instructor Note:Lecture 8

Text book:

AbsoluteJava, Savitch,W.&Mock, K., 5th Edition(2012), Pearson

29

LAB # 05

1) StageJ(Journey)

Introduction

Passing Method Arguments by Value

In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This fact means that any changes to the arguments exist only within the scope of the method. When the method returns, the changes to the arguments are lost.

Non-primitive data type arguments, such as sObjects, are also passed into methods by value. This fact means that when the method returns, the passed-in argument still references the same object as before the method call and can't be changed to point to another object. However, the values of the object's fields can be changed in the method.

The following are examples of passing primitive and non-primitive data type arguments into methods.

Example: Passing Primitive Data Type Arguments

This example shows how a primitive argument of type String is passed by value into another method. The debugStatusMessage method in this example creates a String variable, msg, and assigns it a value. It then passes this variable as an argument to another method, which modifies the value of this String. However, since String is a primitive type, it is passed by value, and when the method returns, the value of the original variable, msg, is unchanged. An assert statement verifies that the value of msg is still the old value.

public class PassPrimitiveTypeExample {

    public static void debugStatusMessage() {

        String msg = 'Original value';

        processString(msg);

        // The value of the msg variable didn't

        // change; it is still the old value.

        System.assertEquals(msg, 'Original value');

    }

    public static void processString(String s) {

        s = 'Modified value';

    }

}

30

Example: Passing Non-Primitive Data Type Arguments

This example shows how a List argument is passed by value into another method and can be modified. It also shows that the List argument can’t be modified to point to another List object. First, the createTemperatureHistory method creates a variable, fillMe, that is a List of Integers and passes it to a method. The called method fills this list with Integer values representing rounded temperature values. When the method returns, an assert verifies that the contents of the original List variable has changed and now contains five values. Next, the example creates a second List variable, createMe, and passes it to another method. The called method assigns the passed-in argument to a newly created List that contains new Integer values. When the method returns, the original createMe variable doesn’t point to the new List but still points to the original List, which is empty. An assert verifies that createMe contains no values.

public class PassNonPrimitiveTypeExample {

    public static void createTemperatureHistory() {

        List<Integer>fillMe = new List<Integer>();       

        reference(fillMe);

        // The list is modified and contains five items

        // as expected.

        System.assertEquals(fillMe.size(),5);       

        List<Integer>createMe = new List<Integer>();

        referenceNew(createMe);

        // The list is not modified because it still points

        // to the original list, not the new list

        // that the method created.

        System.assertEquals(createMe.size(),0);    

    }

            

    public static void reference(List<Integer> m) {

31

        // Add rounded temperatures for the last five days.

        m.add(70);

        m.add(68);

        m.add(75);

        m.add(80);

        m.add(82);

    }   

    public static void referenceNew(List<Integer> m) {

        // Assign argument to a new List of

        // five temperature values.

        m = new List<Integer>{55, 59, 62, 60, 63};

    }   

}

2) Stage a1 (apply)Syntax difference java and c++Creating/Defining a Class with only data members:

32

Object as Function Arguments: We already used this concept in previous lab, when creating Copy Constructorlike: Student s1=new student(15,"Ali"); // create s1 object. Student s2=new Student(s1); // create s2 object by passing s1 as argument Then implementing copy construer like:

Student(Student s) { id=s.id; name=s.name; }: Import scanner class importjava.util.Scanner; class GetInputFromUser{ publicstaticvoidmain(String args[]) { inta; float b; String s; Scanner in =new Scanner(System.in); System.out.println("Enter a string"); s = in.nextLine(); System.out.println("You entered string "+s); System.out.println("Enter an integer"); a = in.nextInt(); System.out.println("You entered integer "+a); System.out.println("Enter a float"); b = in.nextFloat(); System.out.println("You entered float "+b); }

33

}

3) Stage v (verify)

Activity 1:

Make a class called MyCircle, which models a circle. The class contains:

One private instance variables: radius (int). A constructor that constructs a circle with the given radius. Write getter to get radius of the circle. Write setter to set the radius of the circle. A getArea() method that returns the area of the circle in float. A getCircumference() method that returns the circumference of the circle.

Area of Circle = πr2

Circumference of Circle= 2 πr Create main class that construct two circle, assign radius to both circles and display their respective area and circumference.

Activity 2:

Create a class called Account that a bank might use to represent customers' bank accounts. Your class should include one data member of type float to represent the account balance. Your class should provide a constructor that receives an initial balance and uses it to initialize the data member. The constructor should validate the initial balance to ensure that it is greater than or equal to 0. If not, the balance should be set to 0 and the constructor should display an error message, indicating that the initial balance was invalid. The class should provide three member functions. Member function credit should add an amount to the current balance. Member function debit should withdraw money from the Account and should ensure that the debit amount does not exceed the Account's balance. If it does, the balance should be left unchanged and the function should print a message indicating "Debit amount exceeded account balance." Member function getBalance should return the current balance.

4) Stage a2 (assess)Through viva or practical demonstration.

34

Statement Purpose:This lab gives the concept of Object-Oriented Idioms forEncapsulation:Privacyand VisibilityofClass Members, and package access

Activity Outcomes:

After completing this lab the student should be able to: Understand Encapsulation concepts Understand and implement privacy and visibility of class members

Instructor Note:Lecture 9

Text book:

AbsoluteJava, Savitch,W.&Mock, K., 5th Edition(2012), Pearson

35

LAB # 07

1) StageJ(Journey)

Introduction

In general, encapsulation is the inclusion of one thing within another thing so that the included thing is not apparent. Decapsulation is the removal or the making apparent a thing previously encapsulated.

In object-oriented programming, encapsulation is the inclusion within a program object of all the resources need for the object to function - basically, the methods and the data. The object is said to "publish its interfaces." Other objects adhere to these interfaces to use the object without having to be concerned with how the object accomplishes it. The idea is "don't tell me how you do it; just do it." An object can be thought of as a self-contained atom. The object interface consists of public methods and instantiated data.

2) Stage a1 (apply)Code 1:

publicclassEncapsulationDemo{privateintssn;privateStringempName;privateintempAge;

//Getter and Setter methodspublicintgetEmpSSN(){returnssn;

36

}

publicStringgetEmpName(){returnempName;}

publicintgetEmpAge(){returnempAge;}

publicvoidsetEmpAge(intnewValue){empAge=newValue;}

publicvoidsetEmpName(StringnewValue){empName=newValue;}

publicvoidsetEmpSSN(intnewValue){ssn=newValue;}}publicclassEncapsTest{publicstaticvoid main(Stringargs[]){EncapsulationDemoobj=newEncapsulationDemo();obj.setEmpName("Mario");obj.setEmpAge(32);obj.setEmpSSN(112233);System.out.println("Employee Name: "+obj.getEmpName());System.out.println("Employee SSN: "+obj.getEmpSSN());System.out.println("Employee Age: "+obj.getEmpAge());}}

Output:

EmployeeName:MarioEmployee SSN:112233EmployeeAge:32

Code 2:

/* File name : EncapTest.java */

publicclassEncapTest{

privateString name;

privateStringidNum;

privateint age;

publicintgetAge(){

return age;

}

publicStringgetName(){

return name;

37

}

publicStringgetIdNum(){

returnidNum;

}

publicvoidsetAge(intnewAge){

age =newAge;

}

publicvoidsetName(StringnewName){

name =newName;

}

publicvoidsetIdNum(StringnewId){

idNum=newId;

}

}

Output

Name : James Age : 20

3) Stage v (verify)Activity 1:

Write the code to package he common characteristics and behaviors of a person into a single unit: the Person class.

Activity 2:

Then hide the implementation details of the Person class from other objects.

Activity 3:

Modify the Person class above, using “private” to prevent the attributes name and age from being modified by other objects:

4) Stage a2 (assess)Through viva or practical demonstration.

38

Statement Purpose:This lab gives the concept of Static data and methods.

Activity Outcomes:After completing this lab, the student should be able to: Static data and methods

Instructor Note:Lecture 10

Text book:

AbsoluteJava, Savitch,W.&Mock, K., 5th Edition(2012), Pearson

39

LAB # 08

1) StageJ(Journey)

Introduction

Static keyword

What is the meaning of static? The word refers to something that is stationary, stopped and not moveable. What are the types of these variables, declared as static? How can we make use of them? Static as the word implies are variables which exist for a certain amount of time, much longer than that by ordinary automatic variables.

Let‟s consider the example about the lifetime of data variables. One of the variable types is global variable. Global variables are those that are defined outside of main. They are written as standalone statements before main function as inti; the variable iis a global variable. It is not only accessible in main but also in all the functions. They can assign some value to ior obtain the value of i. Global variables come into existence whenever we execute the program and the memory is allocated for i. It exists all the time when the program is running. At the end of the program execution, the memory will be de-allocated and returned to the operating system. So it has a very long lifetime. We need a value which exists for the complete execution of the program and is available in all the functions. We use global variables. It is not a good idea to do that unless it is absolutely necessary. The major plus point of these variables is that these are accessible from everywhere in the program. The inconvenience is that theses variables are visible in those functions too which does not need them.

40

Suppose, we have a global variable ideclared as inti; and in some function we are writing a for loop as for(i = 0; i< n; i++); Now which iis being used here. This is the variable i, declared as global. This global imay have some valuable value, like the number of cars or the number of students etc. Here, in the function when we run the loop, the value of iwill be changed. The global variables have this bad habit of being around, even when we don‟t need them. What will happen if we declare another ivariable inside the function? A local variable will be created inside the function at run time and the global iis not going to be accessible. But this can be very subtle and hard to track programming errors. These are not syntax errors but logical ones. So beware of using too many global variables.

Now have a look on the other side of the picture. While writing functions, we pass values to them. So instead of passing the value of iagain and again, we declare it as global. Now it is available in the function, leaving no need of passing it. Let‟s now come to the next variety of variables. The variables, defined in the main function are local to the function main. It means that they are accessible in all parts of the main function. Their values can be assigned, used in computations and later displayed. When we enter some function other than main, these variables are not accessible there. They are hidden. The global and the local variables, declared in a function are visible. The arguments passed to a function, are also visible. We pass the parameters through stack. Parameters are written on the stack. Later, the function is called which reads from the stack and makes a temporary copy for its use. The variables, declared and used inside the function are called automatic variables. They automatically come into being when the function is called. When the function finishes, these variables are destroyed. So automatic variables are created constantly and destroyed all the time. Here, we are talking about variables ordinary as well as user defined objects. Their behavior is same. They are automatic when the function is called, memory is allocated normally on the stack at the same time and used. When the function exits, these variables are destroyed. What happens if we want that when the function exits, some value, computed inside the function, is remembered by the function and not destroyed. This should not be visible by the other parts of the program.

2) Stage a1 (apply)Code 1:

/* This is a simple program. This shows the use of static variables inside a function. */

#include <iostream.h>

void staticVarFun();

void nonstaticVarFun();

void main(void)

{ cout<< "\nCalling the function which is using static variable \n";

for (inti = 0; i< 10; i++) staticVarFun();

cout<< " \nCalling the function which is using automatic variable \n";

for (inti = 0; i< 10; i++)

41

nonstaticVarFun();

}

// function definiition using static variables

void staticVarFun()

{ static inti = 0;

i++;

cout<< "The value of i is:" <<i<<endl;

}

// function definiition using automatic variables

void nonstaticVarFun()

{

inti = 0;

i++;

cout<< "The value of i is:" <<i<<endl;

}

Output:

Calling the function which is using static variables

The value of i is: 1

The value of i is: 2

The value of i is: 3

The value of i is: 4 T

he value of i is: 5

The value of i is: 6

The value of i is: 7

The value of i is: 8

The value of i is: 9

The value of i is: 10

Calling the function which is using automatic variables

42

The value of i is: 1

The value of i is: 1

The value of i is: 1

The value of i is: 1

The value of i is: 1

The value of i is: 1

The value of i is: 1

The value of i is: 1

The value of i is: 1

The value of i is: 1

Code 2:

//An example of static objects, notice the sequence of their creation and destruction

#include <iostream.h>

// defining a sample class

class truck

{

private:

char name; // Identifier

public:

// constructor displaying the output with the object name

truck(char cc)

{

name = cc;

cout<< "Inside the constructor of " << name <<endl;

}

// destructor displaying the output with the object name

43

~truck() {

cout<< "Inside the destructor of " << name <<endl;

}

};

// defining a global object

truck A('A');

// a simple function creating an object

void f()

{

truck C('C');

}

// a simple function creating a static object

void g()

{

static truck D('D');

}

// main function

int main()

{

// an ordinary object

truck B('B');

// calling the functions

f();

g();

}

Output:

Inside the constructor of A Inside the constructor of B

44

Inside the constructor of C Inside the destructor of C Inside the constructor of D Inside the destructor of B Inside the destructor of D Inside the destructor of A

3) Stage v (verify)

Activity 1:

What is the difference between a static member and a const member?

Activity 2:

Write a class that counts how many instances of that class are currently allocated. Give that class two constructors, each of which has a static variable that counts how many times that constructor has been called. Check that the sum of those two values is equal to the counter.

Activity 3:

Make a simple program to calculate the circumference and the area of a circle. Use „static‟ where appropriate. Use constructors to assign default values to the data members of the object. Afterwards, use member functions to perform the calculation and display the result.

4) Stage a2 (assess)Through viva or practical demonstration.

45

Statement Purpose:This lab helps to get familiar with concept of Inheritance.

Activity Outcomes:After completing this lab, the student should be able to:

get basic understanding of inheritance concept inOOP derive class(es) from other base class(es) throughinheritance

Instructor Note:

46

LAB # 09

Lecture 13

Text book:

AbsoluteJava, Savitch,W.&Mock, K., 5th Edition(2012), Pearson

1) StageJ(Journey)

Introduction

Inheritance:

Inheritance is the way for building new classes from existing classes. This is one of the strongest features of OOP. It is mainly because of this feature, we can claim that we can reuse the existing code. Now the question arises that how we can reuse code? The answer is very simple. Suppose we have two classes which are named as class A and class B. We also suppose that class A is the parent class and class B is the child or inherited class. Further suppose that the parent class carries four methods, one for setting name, one for displaying name, one for setting DOB and one for displaying DOB. Now coming towards child class we are supposing that it owns two method, one for setting registration number and the other for displaying the registration number. According to the doctrine of inheritance we can say with full confidence that without mentioning the child class, which in this case is class B, by default contains the public methods of the parent class, which in our case is class A. So according to this feature, it can be safely concluded that class B contains six methods.

Mathematically speaking there are three important reasons for employing the concept of inheritance:

47

The base class may be used by the other programs and you want its original behavior to remain intact for those programs that already use it. By deriving a class form the base, you define a new data type that inherits all the characteristics of the base class with changing the base class’s operation in other programs.

The source code for base class may not be available. If you are using class libraries from other sources, you may not have the source code for the member functions and you could not change it.

The base class may be an abstract base class, which is one designed to be a base class only. A class hierarchy can contain general purpose classes that do nothing on their own. Their purpose is to define the behavior of a generic data structure to which derived classes add implementation details.

Two terms are strongly related with the concept of inheritance:

Base Class Derived Class

The class from which we build new class would be termed as base class and the new class would be termed as derived class. Now: in object oriented design (OOD) the base class is referred as super class and the derived class is called as subclass.

Caution: Any class can be a base class in the derivation. Base classes have no special code features.

A derived class contains all the member and functions of a base class. The derived class can add new member variables and new member functions. The additional functions are often called incremental function and additional data is often called incremental data.

From coding perspective, the primary benefit of derivation is:

Higher level of code modularization and localization.

Code is easier to maintain and modify.

Instead of duplicating the variables and code of a base class when building a derived class, the derived class incorporates the existing code of the base class.

Type of Inheritance:

C++ provides three types of inheritance:

Public Private Protected

With public inheritance, every object of a derived class may also be treated as an object of that derived class‟s base class.

With protected inheritance, derived classes and their friends can access protected base class members, whereas non friends non derived class member may cannot.

48

Caution: A derived class cannot access the private members of its base class. A derived class can, however, access the public and protected members of its base class. Base class members that should not be accessible to a derived class through inheritance are declared private in the base class. A derived class can access private members of the base class only through access functions provided in the base class public and protected interfaces.

2) Stage a1 (apply)Code 1:

49

Please note that in the main function of the above program we have invoked the volume function. This function is written in the base class, so the derived class has full access over this function.

50

3) Stage v (verify)Activity 1:

Develop a class named person which can perform the following functionality:

a) can set date of birthb) can print namec) can print nationalityd) print date of birth.

Now inherit a class named student from the class person, that can perform the above listed task and in addition, the new class should also perform the following functions.

a) Can set his date of graduationb) Can display his date of graduationc) Can set his GPAd) Can display his GPA.

Activity 2:

Develop a class named shape, which can perform the following functions:

a) Can set the name of shape, i.e. Square, Rectangle, Triangle etc.b) Can display the name of shape

Now inherit three classes from the base class shape: Square, Rectangle and Triangle. All these classes can perform the following tasks:

a) Can find the area of Square, Rectangle and Triangleb) Can display the area of square, Rectangle and Triangle

4) Stage a2 (assess)Through viva or practical demonstration.

51

Statement Purpose:This lab helps to get familiar with concept of Overriding and Overloading.

Activity Outcomes:After completing this lab, the student should be able to:

Understand function overloading within aclass Understand function overriding concerning inheritance classhierarchy Differentiate between function overloading and functionredefining

Instructor Note:Lecture 14

Text book:

AbsoluteJava, Savitch,W.&Mock, K., 5th Edition(2012), Pearson

52

LAB # 10

1) StageJ(Journey)

Introduction

Function overloading is the availability of various functions within a class that differ from each other in function signature i.e. various functions share same name with different parameter types or number of parameters. Inheritance is not necessarily required to overload functions within aprogram.

On the other hand, in function overriding, there must exists inheritance relationship between classes (i.e. base and derived) and functions’ signature are also required to be same in both parent and child class(es). However, derived class(es) redefine function(s) having signature similar to base class’s function(s).

Following code provides an example where both concepts (function overloading and overriding) have been elaborated:

classBase

{

protected:

void myFunc()

{

cout<<"Base Class’ Function";

}

};

class Derived: publicBase

{

public:

void myFunc()

{

cout<<"Derived Class’ Function";

}

voidmyFunc(int a)

{

cout<<"Derived Class’ Function with Parameter Value" <<a;

}

};

53

In the given example (above), At first, the class Derived shows function overloading while containing two

functions differ from each other in function signature (i.e. functions myFunc() andmyFunc(int))

Secondly, it also shows function overriding as it holds two function implementations with same signature (i.e. besides myFunc() of its own, it also contains myFunc() inherited from the Baseclass.

Function overloading and function overriding are the two key concepts of a number of modern computer programming languages.

Overloaded functions provide specific functionalities while taking into account the type/number of parameter(s) they receive and the fundamental advantage is the cleanliness of code. For example, in the absence of overloading, a computer program may have several functions with different names to calculate the area of a geometric shape as shown below:

class

GeometricShape{ public:

int squareArea(intsideLength);

int reactangleArea(int length, intwidth);

int triangleArea(int side1, int side2, intside3);

};

However, the same code with function overloading would be as

class

GeometricShape{ public:

int area(intsideLength);

int area(int length, intwidth);

int area(int side1, int side2, intside3);

};

On the other hand, function overriding is the ability of redefining a specific behavior (function) of a base class within derived class(es). Besides the provisioning of a specific modified implementation of a base class function, function overriding is used to perform runtimepolymorphism.

54

2) Stage a1 (apply)Code 1:

Figure 1: Function Overloading

55

Figure 2: Main( ) function for Figure 1

CompilationAfter writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings that are present in your code.

Executing theProgramA sample output after running the program is shown below:

3) Stage v (verify)Activity 1:

Write a C++ program that can perform the following operations:

a) Addition

56

b) Subtractionc) Multiplicationd) Division

Use operator overloading for the following class:

class number

{

float value;

}

4) Stage a2 (assess)Through viva or practical demonstration.

57

Statement Purpose:This lab helps to get familiar with concept Interfaces and their usage, and abstract classes.

Activity Outcomes:After completing this lab, the student should be able to:

Understand interfaces through implementation Understand their practical usage Understand abstract classes and implement them

Instructor Note:Lecture 16,18

Text book:

AbsoluteJava, Savitch,W.&Mock, K., 5th Edition(2012), Pearson

58

LAB # 11

1) StageJ(Journey)

Introduction

Abstract class in Java

A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body).

Before learning java abstract class, let's understand the abstraction in java first.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java 1.Abstract class (0 to 100%) 2.Interface (100%)

Abstract class in Java

A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.

Abstract method A method that is declared as abstract and does not have implementation is known as abstract method.

What is an interface?

Interface looks like class but it is not a class. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (only method signature, no body). Also, the variables declared in an interface are public, static & final by default. Later we will discuss these points in detail.

What is the use of interfaces?

As mentioned above they are used for abstraction. Since methods in interfaces do not have body, they have to be implemented by the class before you can access them. The class that implements interface must implement all the methods of that interface. Also, java programming language does not support multiple inheritance, using interfaces we can achieve this as a class can implement more than one interfaces, however it cannot extend more than one classes.

59

2) Stage a1 (apply)

60

In the program above, “Demo” class is implementing only one interface “Inf2” however it has to provide the implementation of all the methods of interface “Inf1” too, because interface Inf2 extends Inf1.

Key points: Here are the key points to remember about interfaces:

1) We can’t instantiate an interface in java.

2) Interface provides complete abstraction as none of its methods can have body. On the other hand, abstract class provides partial abstraction as it can have abstract and concrete(methods with body) methods both.

3) implements keyword is used by classes to implement an interface.

4) While providing implementation in class of any method of an interface, it needs to be mentioned as public.

5) Class implementing any interface must implement all the methods, otherwise the class should be declared as “abstract”.

6) Interface cannot be declared as private, protected or transient.

7) All the interface methods are by default abstract and public.

8) Variables declared in interface are public, static and final by default.

61

14) A class cannot implement two interfaces that have methods with same name but different return type.

62

3) Stage v (verify)Activity 1:

Write a Program that implements Base class calculator and a Derived class scientific calculator, The Derived class should take the basic operations i.e. add, divide, subtract from calculator. However it should have its own methods such as square, cube, average.

4) Stage a2 (assess)Through viva or practical demonstration.

63

Statement Purpose:This lab helps to get familiar with concept of Polymorphism and its implementation.

Activity Outcomes:After completing this lab, the student should be able to:

Distinguish between static binding and dynamicbinding Understand polymorphism and dynamic binding while using virtualfunctions Declare abstract classes with pure virtualfunction

Instructor Note:Lecture 19

Text book:

AbsoluteJava, Savitch,W.&Mock, K., 5th Edition(2012), Pearson

64

LAB # 13

1) StageJ(Journey)

Introduction

Polymorphism

Virtual means existing in appearance but not in reality. When virtual functions are used, a program that appears to be calling a function of one class may in reality be calling a function of different class.

The Purpose of Virtual Functions: In order to understand the objective of virtual functions, please consider the following assumption. Suppose we have three different classes called line, circle and triangle. Each class contains a draw() function to draw the relevant shape on the screen. If we want to draw a picture containing numerous lines, circles and triangles we can create an array of pointers which would hold addresses of all the objects in the picture. The array definition may look like this.

Shape *arr[50];

When its time to draw the picture we simply run the loop.

For(I=0; I<50;I++)

Arr[I] -> draw();

2) Stage a1 (apply)

65

Figure 1: Polymorphism

Figure 2: Main( ) function for Figure 1

66

CompilationAfter writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings that are present in your code.

Executing theProgramA sample output after running the program is shown below:

3) Stage v (verify)Activity 1:

Create an abstract class Faculty with fields name and ID. Provide a pure virtual function salary().

Derive a class Permanent Faculty from Faculty. The class has additional attributes years of service and basic pay. The salary of permanent faculty is computed as the sum of basic pay, medical allowance and house rent. Medical allowance is 10% of basic pay and house rent is 25% of the basic pay.

Derive another class Visiting Faculty from Faculty. The class has attributes per hour rate and number of hours taught. The salary of visiting faculty is computed by multiplying the per hour rate with the number of hours taught.

Write a program to declare two pointers of class Faculty. Create an object each of visiting and permanent faculty, assign their addresses to pointers of base class, set the values of data members and call the salary function for each.

Activity 2:

Modify the above program to declare an array of pointers to Faculty. Using dynamic memory allocation, create an object of permanent or visiting faculty as indicated by the user (Get user choice).

Once the user has entered data for faculty, call the salary method for each object and display the salary.

4) Stage a2 (assess)Through viva or practical demonstration.

67

LAB # 14

Statement Purpose:This lab helps to get familiar with concept of Exception handling basics and throwing exceptions in methods. It also helps to understand file handling.

Activity Outcomes:After completing this lab, the student should be able to:

understand the limitations of conventional error-handling techniques. understand various types of exceptions and exception handling mechanism. use of try-catch blocks to handle exceptions. use of multiple catch blocks with a single try block. understand the benefits of exception handling. know how to deal with exceptions using C++ standard exception classes.

Instructor Note:Lecture 22, 23

Text book:

AbsoluteJava, Savitch,W.&Mock, K., 5th Edition(2012), Pearson

68

1) StageJ(Journey)

Introduction

What is an exception? An Exception can be anything which interrupts the normal flow of the program. When an exception occurs program processing gets terminated and doesn’t continue further. In such cases we get a system generated error message. The good thing about exceptions is that they can be handled. When an exception can occur? Exception can occur at runtime (known as runtime exceptions) as well as at compile-time (known Compile-time exceptions). Reasons for Exceptions An exception can occur for many different reasons, below given are some scenarios where exception occurs. A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications or the JVM has run out of memory.

Difference between error and exception Errors indicate serious problems and abnormal conditions that most applications should not try to handle. Error defines problems that are not expected to be caught under normal circumstances by our program. For example memory error, hardware error, JVM error etc. Exceptions are conditions within the code. A developer can handle such conditions and take necessary corrective actions. Few examples – DivideByZero exception NullPointerException ArithmeticException ArrayIndexOutOfBoundsException

Types of exceptions There are two types of exceptions:

Checked exceptions Unchecked exception

Checked exceptions All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the program, it will give compilation error. Examples of Checked Exceptions:- Class Not Found Exception Illegal Access Exception No Such Field Exception EOF Exception etc. Unchecked Exceptions Runtime Exceptions are also known as Unchecked Exceptions as the compiler do not check whether the programmer has handled them or not but it’s the duty of the programmer to handle these exceptions and provide a safe exit. These exceptions need not be included in any method’s throws list because compiler does not check to see if a method handles or throws these exceptions. Examples of Unchecked Exceptions:- Arithmetic Exception Array Index Out Of Bounds Exception Null Pointer Exception Negative Array Size Exception etc.

69

What is Try Block? The try block contains a block of program statements within which an exception might occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block. A try block must followed by a Catch block or Finally block or both. Syntax of try block try{ //statements that may cause an exception } What is Catch Block? A catch block must be associated with a try block. The corresponding catch block executes if an exception of a particular type occurs within the try block. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes.

2) Stage a1 (apply)

Code 1:

Code 2:

70

Figure 1: Exception Code

Figure 2: Main function for Figure 1

Output:

71

3) Stage v (verify)Activity 1:

Create a class Student with data member’s age and marks, both of type integer. Provide a parameterized constructor and a set member function to set the data members. The age should be a positive number between 15 and 40 while the marks should be between 0 and 100. Create a class Invalid Range as exception handler of the Student class. The student class should throw an exception if any of its member functions attempts to assign an invalid value to the data members.

In the main program, create objects of class student, assign valid/invalid values to the data members and catch the exceptions accordingly.

Activity 2:

Modify the above program to add two private data members (a string and an integer) to the class InvalidRange. Provide appropriate constructor and get methods for the data members. The string should store the name of the function throwing the exception while the integer should store the invalid value the user has supplied.

4) Stage a2 (assess)Through viva or practical demonstration.

72

Statement Purpose:This lab helps to get familiar with concept of Swing GUI controls and its implementation.

Activity Outcomes:After completing this lab, the student should be able to:

Able to create JAVA based Front End/ GUI Applications create Graphical User Interface in platform independent way by using

rich libraries

Instructor Note:Lecture 28

Text book:

AbsoluteJava, Savitch,W.&Mock, K., 5th Edition(2012), Pearson

73

LAB # 15

1) StageJ(Journey)

Introduction

JAVA provides a rich set of libraries to create Graphical User Interface in platform independent way. In this article we'll look in SWING GUI controls. Swing API is set of extensible GUI Components to ease developer's life to create JAVA based Front End/ GUI Applications. It is build upon top of AWT API and acts as replacement of AWT API as it has almost every control corresponding to AWT controls. Swing features

Light Weight - Swing component are independent of native Operating System's API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls.

Rich controls - Swing provides a rich set of advanced controls like Tree, slider, colorpicker, table controls

Highly Customizable - Swing controls can be customized in very easy way as visual apperance is independent of internal representation.

Pluggable look-and-feel- SWING based GUI Application look and feel can be changed at run time based on available values.

JFrame – A frame is an instance of JFrame. Frame is a window that can have title, border, menu, buttons, text fields and several other components. A Swing application must have a frame to have the components added to it. JPanel – A panel is an instance of JPanel. A frame can have more than one panels and each panel can have several components. You can also call them parts of Frame. Panels are useful for grouping components and placing them to appropriate locations in a frame. JLabel – A label is an instance of JLabel class. A label is unselectable text and images. If you want to display a string or an image on a frame, you can do so by using labels. In the above example we wanted to display texts “User” & “Password” just before the text fields , we did this by creating and adding labels to the appropriate positions. JTextField – Used for capturing user inputs, these are the text boxes where user enters the data.

JPasswordField – Similar to text fields but the entered data gets hidden and displayed as dots on GUI. JButton – A button is an instance of JButton class. In the above example we have a button “Login”.

2) Stage a1 (apply)

Code 1:

74

75

3) Stage v (verify)Activity 1:

Create several panels and add them to specific positions in a JFrame. Inside panels add text fields, buttons and other components.

4) Stage a2 (assess)Through viva or practical demonstration.

76