You are on page 1of 71

Lab Guide for Object Oriented Programming Using Java

Author(s)
Authorized by
Creation/Revision Date
Version

S.Meenakshi
Lesitha Mary James
Mr. Srikantan Moorthy
Mar-2009/Aug-2009
1.2

CONFIDENTIAL

COPYRIGHT NOTICE
All ideas and information contained in this document are the intellectual property of
Education and Research Department, Infosys Technologies Limited. This document is
not for general distribution and is meant for use only for the person they are
specifically issued to. This document shall not be loaned to anyone, within or outside
Infosys, including its customers. Copying or unauthorized distribution of this
document, in any form or means including electronic, mechanical, photocopying or
otherwise is illegal.
Education and Research Department
Infosys Technologies Limited
Electronic City
Hosur Road
Bangalore - 561 229, India.
Tel: 91 80 852 0261-270
Fax: 91 80 852 0362
www.infosys.com
mailto:E&R@infosys.com

CONFIDENTIAL

Infosys Technologies Limited

Document Revision History

Document Revision History


Version
1.0

Date
Mar-2009

1.1

Jun-2009

1.2

Aug-2009

ER/CORP/CRS/ LA1026
i

Author(s)
Vani Vasudevan
Lesitha Mary James
S.Meenakshi
Lesitha Mary James

Reviewer(s)
Meenakshi S
Nishit Goel
Nishit Goel

S.Meenakshi
Lesitha Mary James

Nishit Goel

CONFIDENTIAL

Comments
Restructure 2009
Changes made as per
feedback from pilot batch
rollout

Modified
assignments
based on case study

Version No: 1.2

Infosys Technologies Limited

Object Oriented Programming using Java

Contents

COPYRIGHT NOTICE ...................................................................................................... II


DOCUMENT REVISION HISTORY ......................................................................................... I
CONTENTS ..................................................................................................................1
CONTEXT ....................................................................................................................3
DAY 1 ASSIGNMENTS .....................................................................................................3
ASSIGNMENT 1: CASE STUDY .................................................................................................. 3
ASSIGNMENT 2: OOP FEATURES ............................................................................................... 4
ASSIGNMENT 3: CLASSES AND OBJECTS ........................................................................................ 5
ASSIGNMENT 4: FIRST JAVA PROGRAM ........................................................................................ 6
ASSIGNMENT 5: LOCAL VARIABLES ............................................................................................. 8
ASSIGNMENT 6: OPERATORS ................................................................................................... 9
ASSIGNMENT 7: BOOLEAN DATA TYPE ....................................................................................... 10
ASSIGNMENT 8: BYTE DATA TYPE ........................................................................................... 11
DAY 2 ASSIGNMENTS ................................................................................................... 12
ASSIGNMENT 1: TYPECASTING ............................................................................................... 12
ASSIGNMENT 2: CONTROL STATEMENT ...................................................................................... 13
ASSIGNMENT 3: SWITCH CASE STATEMENT ................................................................................... 14
ASSIGNMENT 4: CLASSES AND OBJECTS ...................................................................................... 15
ASSIGNMENT 5: DEFAULT CONSTRUCTOR .................................................................................... 16
ASSIGNMENT 6: DEFAULT AND PARAMETERIZED CONSTRUCTORS.............................................................. 17
ASSIGNMENT 7: PASS BY VALUE AND REFERENCE............................................................................. 18
ASSIGNMENT 8: CODING STANDARDS ......................................................................................... 19
ASSIGNMENT 9: USAGE OF THIS KEYWORD ................................................................................ 20
SELF REVIEW ................................................................................................................ 21
DAY 3 ASSIGNMENTS ................................................................................................... 23
ASSIGNMENT 1:STATIC VARIABLE, BLOCK AND METHOD....................................................................... 23
ASSIGNMENT 2: 2D ARRAYS .................................................................................................. 24
ASSIGNMENT 3: MULTIDIMENSIONAL ARRAY(JAGGED ARRAY) ................................................................ 25
ASSIGNMENT 4:STRINGS ..................................................................................................... 25
ASSIGNMENT 5: JAVA DOC EXPLORATORY ASSIGNMENT ...................................................................... 27
ASSIGNMENT 6: USER INPUT(COMMAND LINE ARGUMENT) ................................................................... 27
ASSIGNMENT 7:COMMAND LINE ARGUMENT .................................................................................. 28
ASSIGNMENT 8:OVERLOADED METHODS ...................................................................................... 29
SELF REVIEW ................................................................................................................ 30
DAY 4 ASSIGNMENTS ................................................................................................... 33
ASSIGNMENT 1: INHERITANCE ................................................................................................ 33

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2

1 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

ASSIGNMENT 2: PROTECTED ACCESS SPECIFIER ............................................................................ 34


ASSIGNMENT 3: METHOD OVERRIDING ,SUPER KEYWORD AND DYNAMIC BINDING ............................................. 36
ASSIGNMENT 4: SUPER KEYWORD ............................................................................................ 38
ASSIGNMENT 5: CONSTRUCTOR INVOCATION ................................................................................. 42
ASSIGNMENT 6 : DYNAMIC POLYMORPHISM ................................................................................... 44
ASSIGNMENT 7:FINAL KEYWORD .............................................................................................. 45
ASSIGNMENT 8:ABSTRACT CLASS ............................................................................................ 47
REVIEW ...................................................................................................................... 48
DAY 5 ASSIGNMENTS ................................................................................................... 52
ASSIGNMENT 1: PACKAGE (CREATE, COMPILE & EXECUTE ) ................................................................. 52
ASSIGNMENT 2 : ACCESS SPECIFIER.......................................................................................... 57
ASSIGNMENT 3:INTERFACES .................................................................................................. 59
ASSIGNMENT 4: UML USE CASE DIAGRAM ................................................................................. 60
ASSIGNMENT 5: UML CLASS DIAGRAM ..................................................................................... 61
ASSIGNMENT 6: CASE STUDY OF D-RAIL INC. ................................................................................ 62
SELF REVIEW ................................................................................................................. 63
CASE STUDY BASED ASSIGNMENTS .................................................................................. 65
CASE STUDY 1 BANKING SYSTEM ........................................................................................... 65
DAY 2 ASSIGNMENT 1: IF-ELSE CONDITION ................................................................................... 65
CASE STUDY 2 TRAVEL MANAGEMENT SYSTEM.............................................................................. 65
DAY 2 ASSIGNMENT 1: IF-ELSE CONDITION ................................................................................... 65
DAY 3 ASSIGNMENT 2: STRINGS.............................................................................................. 66
DAY 4 ASSIGNMENT 3: INHERITANCE ......................................................................................... 67

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2

2 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Context
This document contains assignments to be completed as part of the hands on for the subject
Introduction to Object Oriented Programming using Java.
Note: In order to complete the course, assignments in this document must be completed in
the sequence mentioned.

Day 1 Assignments
Assignment 1: Case Study
Objective: Analysis of the case study and identify the complex system attributes and using
OO features to overcome the same.
Problem Description: Course Management System
A Course Management System needs to be developed for an engineering college. The college
wants an automated system to replace its manual system for purpose of allocation of students
to courses and lecturers to courses. There are 10000 students and 500 faculty members in the
college. The engineering college provides graduation and post graduation in the various
branches of engineering.
In any branch, the entire duration is divided into semesters. Each semester includes various
courses. Students admitted into the college can apply for various courses. The courses are
elective in nature. The student needs to select two electives. The electives are offered from
5th semester onwards for graduate students and from 3rd semester onwards for the post
graduate students. The graduate students need to undergo a final year project in the fourth
year of engineering whereas the post graduate student undergoes a thesis submission in the
second year. The complete list of courses, lecturers and students is maintained in the college.
The list is constant and cannot be updated by the system. The automated system uses this list
for allocation of courses.
The lecturers can be categorized into full time lecturers and visiting members. The full time
lecturers have target days and are paid salary every month. The visiting members get paid per
lecture basis and do not have any target days.
The system is used by the admin staff to register students admitted to college to the courses
opted. The system needs to be authenticated with a login id and password. The system would
be used by the student to view the marks and the attendance details also. The system is used
by the HOD (Head of the department) to allocate courses to the lecturers. At the beginning of
the semester, the HOD will do the allocation of lecturers to the classes for his department.
The HOD may make changes in the allocation during the progress of the course. The system
maintains a history of all the lecturers who have handled the courses throughout the semester
.The lecturer will use the system to update the marks of the student (project, assignment,

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2

3 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

internal test marks and the semester end examination marks). The lecturer will also mark
the attendance of the students through the system.
In addition to the above, the system also keeps track of the residential status of the student.
The student may be a host-elite or a day scholar. If he is host-elite, the system will maintain
his / her hostels name, room number and the fees pertaining to the same.
Answer the following:
a. Identify two cases of hierarchy in the given problem statement
b. Identify the common behavior among the day scholar, host-elite, graduate and post
graduate students
c. Identify the different layers possible in this system in terms of the users of the systems
d. The admin staff wants to generate a report containing the scores of students in a batch in
the following manner:

Student Id Student Name Marks scored Lecturer Name Course registered


What details should the admin staff accumulate to arrive at this detailed report?
Estimated time: 20 mins
Summary of this assignment:
In this assignment, you have learnt
To understand a complex software system and identify the attributes

Assignment 2: OOP features


Objective: Analyze the OOP features
Problem Description: Consider the case study provided in Assignment 1 for this

assignment.
a. Identify the attributes of the Student class. What are the details that can be exposed and
what details can be hidden?
b. Consider the calculation of grade for the Student. There are several student types. Let us
assume that we need to write a method for the calculation. How many methods would be
written? Will they have the same name and signature? Will the functionality /code in
these functions remain same?
c. The fees have to be paid by the host-elite and by the day scholars. The host-elites need to
pay hostel fees along with semester fees. The day scholars need to pay only semester
fees. How many function/s would you code in the Student class and why?
d. For the options a,b and c identify the OOP features that would be implemented
Estimated time: 20 mins
Summary of this assignment:

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2

4 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

In this assignment, you have learnt


Analyze a complex system and apply object oriented approach to solve the problem

Assignment 3: Classes and Objects


Objective: Understand the terms -class, objects, state, behavior and identity
Problem Description: Fill the crossword based on the clues given
1.
2.
3.
4.
5.
6.
7.
8.
9.

Jack is the name of a student- represents ________


Graduates, post graduates , day scholars and host-elites share common behavior of this
________
Tom is a Post Graduate student and is a topper represents _____________
The attribute and the activities related to a student are put as part of Student classrepresents _________________
There is a student in graduation class , whose id is1001 , name Jack and attending
Operating systems course represents an __________________
The student pays fees and the calculation is done by the admin represents _______
A day scholar is a type of student represents ___________
A student can only view marks, he cannot update itrepresents ________________
I use calculateFees method , be it host-elite or day scholar represents
__________________________
8
6

1
2
7
3
9
4

Estimated time: 20 mins


Summary of this assignment:
In this assignment, you have learnt

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2

5 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Object Oriented terminologies

Assignment 4: First Java Program


Objective: Create, save, compile and execute a Java Program using text pad.
Problem Description: To display Welcome message using Java program
Step 1: Go to Start and Run

Step 2: Open textpad

Step 3: Text editor is opened as below

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2

6 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Step 4: Go to File menu and select Save As menu option to save the file as Welcome.java in
the chosen folder (This would enable the java color setting for the code to be typed)

Step 5: Type the below program in the textpad and save


// First Java program
class Welcome{
public static void main(String args[]){
// println method is used to print message on the screen
System.out.println("Welcome to Object Oriented Programming:Day1
Session");
}
}

Step 6: Compile the program (press Ctrl + 1 or go to Tools menu and select Compile Java)

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2

7 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Indicates that compilation is successful


Step 7: Execute the program (press Ctrl + 2 or go to Tools menu and select Run Java
Application
Output Window:

Estimated time: 15 mins


Summary of this assignment:
In this assignment, you have learnt
How to create, save , compile and execute the Java program using textpad

Assignment 5: Local Variables


Objective: Understand the usage of local variables
Problem Description: To create different types of local variables and display them
Step 1: Type the below program in the textpad, save and compile the program
// Program to understand local variables and literals
class Variable {
public static void main (String args[]){
int intVal;
float floatVal = 250.5f;
double doubleVal = 2500.5;
boolean boolVal = true;

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2

8 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

System.out.println("Integer\t:" + intVal + "\nFloat\t:" +


floatVal+"\nDouble\t:" + doubleVal + "\nBoolean\t:" + boolVal);
}
}
Step 2: Observe that there is a compilation error. Debug the code so that it compiles and
executes successfully.

Note: Accessing an uninitialized local variable will result in a compiletime error. If you cannot initialize your local variable where it is
declared, make sure to assign a value before you attempt to use it.

Estimated time: 15 mins


Summary of this assignment:
In this assignment, you have learnt
How to use local variables in Java

Assignment 6: Operators
Objective: Understand the various operators in Java
Problem Description: To implement and understand the usage of modulus operator, string
concatenation, equality operator and logical operators in Java.
Step 1: Type the below program in the textpad, save, compile and execute
// Program to understand different types of operators
class Operator{
public static void main(String[] args){
int intVal=10;
float floatVal=3.0f;
boolean bool1 = true;
boolean bool2 = false;
boolean bool3 = true;

// Arithmetic : Modulus operator


System.out.println("Arithmetic");
System.out.println(intVal + " % " + floatVal + "=" +

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2

9 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

(intVal % floatVal));
System.out.println();
// String Concatenation : Observe the difference
System.out.println("String Concatenation");
System.out.println("Day " + 2 + " Session");
System.out.println("\n" + 2 + 3 +"\n" +(2+3));
System.out.println();
// Relational: Equality operator
System.out.println("Relational");
System.out.println(intVal + " == " + floatVal + " = "
+(intVal==floatVal));
floatVal = 10.0f;
System.out.println(intVal + " == " + floatVal + " = "
+(intVal==floatVal));
System.out.println();
bool2 = false;
if(bool1 || (bool1 && (bool2=false))){
System.out.println("Success");
}
else{
System.out.println("Failure");
}
System.out.println("bool2 value : " + bool2);
}
}
Estimated time: 25 mins
Summary of this assignment:
In this assignment, you have learnt
Usage of some operators available in Java

Assignment 7: Boolean Data Type


Objective: Understand the Boolean data type
Problem Description: To implement and understand the usage Boolean datatype in Java
Step 1: Type the below program in the textpad and save the file
Step 2: When executed, the output is :

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 10 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Failure
bool2 value : true
Press any key to continue . . .
Step 3: Make changes to the code so that the output reads :

Success
bool2 value : true
Press any key to continue . . .
Note: The logical operators and the Boolean operators may be changed to achieve this
result. Although the if control structure is used here, the focus is on the operators and
Boolean datatype

class Operator{
public static void
boolean bool1
boolean bool2
boolean bool3

main(String[] args){
= false;
= true;
= true;

if(bool1 && (bool1 && (bool2=false))){


System.out.println("Success");
}
else{
System.out.println("Failure");
}
System.out.println("bool2 value : " + bool2);
}
}
Summary of this assignment:
In this assignment, you have learnt
Boolean data type and operators
Estimated time: 15 minutes

Assignment 8: Byte Data Type


Objective: Understand the byte data type
Problem Description: Understand the range for datatypes and strong typechecking.
Step 1: Consider the program given below:

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 11 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

public class Operator {


public static void main(String args[]){
int intVal = 100;
byte byteVal= (byte)intVal;
byte max = 127;
byte min = -128;
byte sum= max + min;
System.out.println("Sum= " + sum);
}
}
Step 2: Type the program and compile it
Step 3: Analyze the compilation error
Note: The solution to this error will be dealt with in Day 2 of the course
Estimated time: 20 minutes
Summary of this assignment:
In this assignment, you have learnt
Byte data type

Day 2 Assignments
Assignment 1: Typecasting
Objective: Understand Conversion and Typecasting
Problem Description: Modify Assignment No. 8 of Day 1 so that the addition of the numbers is
possible and can be stored and displayed.
Estimated time: 15 minutes
Summary of this assignment:
In this assignment, you have learnt
Typecasting Data types

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 12 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Assignment 2: Control Statement


Objective: Understand control statements
Problem Description: To implement control flow statements break and continue
Step 1: Type the below programs in the textpad, save, compile and execute
Program 1:
//Program to understand the loop and break
class Control{
public static void main(String args[]){
boolean bool = true;
for(int i= 0; i<5 ; i++){
for(int j = 0; j<10; j++){
System.out.print(j +"\t");
if(j > 5){
break;
}
}
System.out.println("Outer Loop");
}
System.out.println("End");
}
}

Program 2:
//Program to understand the loop and continue
class ControlContinue{
public static void main(String args[]){
boolean bool = true;
for(int i= 0; i<5 ; i++){
for(int j = 0; j<10; j++){
System.out.print(j +"\t");
if(j > 5){
System.out.println();

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 13 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

continue;
}
}
System.out.println("Outer Loop");
}
System.out.println("End");
}
}

Note:
You cant use a number or anything that does not evaluate to a
Boolean value as a condition in selection / iteration statement

You can use break inside a looping statement without including if


construct.

Estimated time: 15 mins


Summary of this assignment:
In this assignment, you have learnt
How to use break and continue with the looping statement.

Assignment 3: Switch case statement


Objective: Understand the concept of conditional case statements using switch cases.
Problem Description: A java program needs to be written to display the range of marks based
on the grade. The table for calculation of grade is as follows:

Grade
A
B
C
D
E

Range of marks
80-100
73-79
65-72
55-64
<55

Step 1: Create a class called SwitchCase with the main method


Step 2: Create a character variable for storing the grade with a default value of B
Step 3: Write the java code to implement the calculation of grades as given in the table. If
any other grade is provided , the program must display a message Grade does not exist,for
valid grades it must display the range of marks as given in the table.

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 14 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Step 4: Change the values of the grade variable and test the working of the program for all
the grades.
Estimated time: 20 minutes
Summary of this assignment:
In this assignment, you have learnt
Switch case statements

Assignment 4: Classes and Objects


Objective: Understand and implement the concept of Abstract Data Type used for achieving
encapsulation and abstraction.
Problem Description:
Implement the following class diagram using Java.
Student
-studentId : integer
-studentType:char
+setStudentId(id:int):void
+setStudentType(type:char):void
+getStudentId():int
+getStudentType():char

Note:
Using a class , you can create any number of objects
For every instance variable there should be a setter and getter
method associated to it. Setter method is to set the value of the
instance variable and getter method is to return the value of the
instance variable
studentType instance variable can have F (fresher) or L (lateral)

Step 1: Define a class Student and save it in Student.java


Step 2: Define all the member methods of Student Class
Step 3: Define a class CourseManagement with main method and save it in
CourseManagement.java
a. In the main method, assign the student details in the corresponding temporary
variables.
b. Create a reference variable with the name student and instantiate the same

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 15 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

c.

Invoke the corresponding setter methods to set the instance variable with the
given values stored in temporary variables.
d. Using getter methods, display the student details.
Step 4: Compile the program, fix the errors if any
Step 5: Execute the program and verify the output
Estimated time: 30 mins
Note:
Create a folder for storing every assignment
Summary of this assignment:
In this assignment, you have learnt
How to implement ADT in Java
How to implement getter and setter methods
How to create reference variables
How to create an object

Assignment 5: Default Constructor


Objective: Understand the concept of Default Constructor.
Problem Description:
Enhance the Assignment 4 and do the necessary modification as mentioned below:
Student
-studentId : integer
-studentType:char
+Student()
+setStudentId(id:int):void
+setStudentType(type:char):void
+getStudentId():int
+getStudentType():char
Step 1: Define constructor in Student class
Student (): initialize the instance variables with 10 and F (indicated fresher)
respectively
Step 2: Define a main method
a. In the main method, create a reference variable with the name student.
b. Create an object of type Student and assign it to reference variable named
student.

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 16 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

c. Using getter methods, display the student details.


Step 3: Compile the program, fix the errors if any
Step 4: Execute the program and verify the output
Estimated time: 15 mins
Summary of this assignment:
In this assignment, you have learnt
How to implement default constructor
How to use the constructor for initializing the objects

Assignment 6: Default and Parameterized constructors


Objective: Understand the concept and working of default and parameterized constructor.
Problem Description: Create a class called UserType and create a default and a
parameterized constructor. Invoke these constructors through two different objects of the
UserType class.
public class UserType {
String name;
UserType(String parameterVal)
{
name = parameterVal;
}
UserType()
{
this("student");
}
public static void main(String args[]) {
UserType usertype1 = new UserType("Faculty");
UserType usertype2 = new UserType();
System.out.println(usertype1.name);
System.out.println(usertype2.name);
}
}
Estimated time: 15 minutes
Summary of this assignment:

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 17 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

In this assignment, you have learnt about


Default and
Parameterized constructors

Assignment 7: Pass By Value and reference


Objective: Understand passing of primitive and abstract data types .
Problem Description: To write code to understand pass by value and passing reference
objects.
Step 1: Consider the program given below:
public class passByVal {

public static void main (String args[]){


int sId = 25;
passByVal val = new passByVal();
System.out.println(sId);
val.passTheValueMethod(sId);
System.out.println("The sId are" + sId);
}
public void passTheValueMethod(int sId)
{
sId = 10;
System.out.println("The sId are" + sId);
}
}
Step 2: Write the necessary code in above given program and compile it.
Step 3: After successful compilation of the program, execute it. Supply the necessary values
and observe the output.
Note: There is no change in the student Id of the student. Why?
Step 5: Enhance this code by passing the object of Student class(created in earlier
assignment) to the method passTheValueMethod().Change the value of Student Id and display
the Student Id of the student.
Note: There is a change in the Student Id. Why?
Estimated time: 20 minutes

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 18 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Summary of this assignment:


In this assignment, you have learnt
Pass by value and Pass by reference

Assignment 8: Coding Standards


Objective: Understand and implement coding standards
Problem Description: Consider the program given below. Correct the missing coding
standards, prevent instance variable hiding , compile and execute the program.
Note: i and j represent instance variables as well as parameters
public class class1 {
int i=22;
int j=14000;
boolean k;
boolean l;
public static void main(String args[]){
i=22;
j=14000;
class1 class1= new class1();
k= class1.Method1(i);
l= class1.Method2(j);
if(k==true &&l==true )
{
System.out.print(" Is a new employee");
}
else
{
System.out.print(" Is not a new employee");
}
}
public boolean Method1(int i)
{
if (i>20 && i<30)
{
return true;
}
else
{
return false;
}

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 19 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

}
public boolean Method2(int j)
{
if (j>=14000 && j<20000)
{
return true;
}
else
{
return false;
}
}
}
Estimated time: 15 minutes
Summary of this assignment:
In this assignment, you have learnt
Coding standards

Assignment 9: Usage of this keyword


Objective: Understand the usage of this keyword.
Problem Description:
Implement the class diagram Using Java
Student
-studentId : integer
-studentType:char
-studentName:String
+Student()
+Student(char sType,String fname,String lname)
+displayDetails(Student):void

Step 1: Define a class Student ,


Define two constructors
o Default constructor: Used to increment the value of studentId for each
objects of Student class. studentId should start from 550.
o Parameterized constructor:
Constructor with three arguments
StudentType(H/D),firstName and lastName

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 20 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

studentName=firstName+lastName
o displayDetails (Student obj):Should accept the object as an argument
and display the details like studentId, studentType, studentName of that
object
Step 2: Define a main method ,
In the main method
o Create an object of Student(D,Bony,Thomas) and assign it to
reference variable studentOne;
o Call the displayDetails() method and display the details of studentOne
o Create an object of Student(H,Dinil,Bose) and assign it to
reference variable studentTwo;
o Call the displayDetails() method and display the details of studentTwo
Step 3: Compile the program, fix the errors if any
Step 4: Execute the program and verify the output
Estimated time: 20 mins
Summary of this assignment:
In this assignment, you have learnt
How to use this, passing object to an argument, Overloaded constructors

Self Review
Predict the output of the following programs and analysis your answer by executing the code:
1.
class TypeCasting{
public static void main(String args[]){
int intVal=10;
double doubleVal= 20.0;
// Explicit Casting is required
intVal = doubleVal;
System.out.println(intVal);
}
}
2.
class Demo{
public static void main(String args[]){
if(1){
System.out.println("True Block");
}
else{
System.out.println("False Block");
}
}

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 21 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

}
Note : You can only the Boolean type in the conditional statement
0 wont be interpreted as false and nonzero (>0) wont be interpreted
as true.
3.
class Example{
public static void main(String[] args){
int intValOne = 0;
int intValTwo = 0;
for(short index=0; index < 5; index++){
if((++intValOne > 2) || (++intValTwo > 2)){
intValOne++;
}
}
System.out.println(intValOne + " " + intValTwo);
}
}

4.
class Example{
public static void main(String[] args){
int intValOne = 5,intValTwo = 7;
System.out.println((( intValTwo * 2) % intValOne));
System.out.println(intValTwo % intValOne);
}
}

5.
class Example{
public static void main(String[] args){
int val1 = 9;
int val2 = 6;
for (int val3 = 0; val3 < 6; va13++,val2--){
if(val1 > 2){
val1--;
}
if(val1 > 5){
System.out.print(val1 + );
--val1;

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 22 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

continue;
}
val1--;
}
}
}
7.
Find the output of the following program:
public class switchCase {
public static void main(String args[])
{
String comment;
int val = (int)(4 * 3);
switch (val) {
case 0: comment = "Case
break;
case 1: comment = "Case
break;
case 2: comment = "Case
break;
default: comment = "Oops
}
System.out.print(comment);
}

0";
1";
2";
-- something is wrong ";

Day 3 Assignments
Assignment 1:Static variable, block and method
Objective: Understand the static variable, static block and static method
Problem Description:
Modify the Assignment 10 of Day 2 to get the total number of student objects
Static variable and static method:

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 23 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Step 1: Add static data member studentCount to store the total number of
objects of
type Student
Step 2: Add static member method getStudentCount () to return the value
studentCount.
Step 3: In default constructor Student(), increment the studentCount by 1 and assign
to studentId
Static block:
Step 4: Assign studentCount = 10 (as already 10 students have enrolled)
Step 5: Save and Compile the program, fix the errors if any
Step 6: Execute the program and verify the output
Estimated time: 20 mins
Summary of this assignment:
In this assignment, you have learnt
How to use static variable, method and block

Assignment 2: 2D arrays
Objective: Understand 2D arrays and its working
Problem Description: Create class DemoArray to add 2D arrays. Write the business logic to
display the sum of the matrices. Below mentioned are a few guidelines that can be followed
Initialize the 2D arrays as follows:
int firstArrayMatrix[][]={{1,1,1},{1,1,1}};
int secondArrayMatrix[][]={{2,2,2},{2,2,2}};

Display the two matrices on the console as follows:


Matrix 1
1 1 1
1 1 1
Matrix 2
2 2 2
2 2 2

Display the sum of the matrices:


Sum of the Matrices
3 3 3
3 3 3

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 24 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Estimated time: 20 minutes


Summary of this assignment:
In this assignment, you have learnt
Implementation of 2d arrays

Assignment 3: Multidimensional Array(Jagged Array)


Objective: Understand the concept of Jagged Array
Problem Description:
The students joined a tutorial for the various subjects as given below:

Tony
Thomas
Dinil

JAVA
JAVA
Linux

C
UNIX
Oracle

C++

Delvin

RDBMS

C#

ORACLE

Initialize the array based on the above table and display the details of Delvin inside the main
method written in a class JaggedArray
Estimated time: 20 min
Summary of this assignment:
In this assignment, you have learnt
Multidimensional Array

Assignment 4:Strings
Objective: To understand the concept of strings
Problem Description:
Enhance the Assignment 5 of Day 2 and do the necessary modification as mentioned below:
Student
-studentId : integer
-studentType:char
-studentName:String
+Student()
+Student(id,type,firstName,lastName)
+setStudentId(id:int):void
ER/CORP/CRS/ LA1026
CONFIDENTIAL
Version No. 1.2 25 of 68
+setStudentType(type:char):void
+setStudentName(firstName:String,lastName:String)
+getStudentId():int

Infosys Technologies Limited

Object Oriented Programming using Java

Step 1: Define constructors in Student class


Student (): Initialize the instance variables with 10 and F (indicated fresher)
respectively
Student(id,type,firstName,lastName):Initialize the instance variables studentId
and studentType with id and type respectively. Initialize the instance variable
studentName with firstName + lastName. (+ denote concatenation)
Step 2: Define the setStudentName(firstName:String,lastName:String) as below:
setStudentName(String firstName,String lastName){
studentName = firstName+lastName;
}
Step 3: Define a main method
a. In the main method, create a reference variable student of type Student.
b. Create an object of type Student and assign it to reference variable named
student.
i. Invoke the corresponding setter methods to set the instance variable
with the given values stored in temporary variables.
ii. Using getter methods, display the student details.
c. Create an object of type Student (id, type, firstName, lastName) and assign
it to reference variable named student.
i. Using getter methods, display the student details
Step 4: Compile the program, fix the errors if any
Step 5: Execute the program and verify the output
Estimated time: 25 mins
Note:
You can refer javadoc to know various methods present in String class

Summary of this assignment:


In this assignment, you have learnt
How to use strings

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 26 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Assignment 5: Java Doc Exploratory assignment


Objective: To explore and understand the Java Doc. Create a program with the help of java
doc. (hint use String)
Problem Description: Create classes called which does the following:
1. Takes User name as input
2. Display length of the string
3. Displays output as Hi <username>
4. Convert User name to lower case
5. Convert User name to upper case
6. Check whether the name is starting with a
7. Replace the User name as INFOSYS
Estimated time: 35 minutes
Summary of this assignment:
In this assignment, you have learnt
To use Java Doc to seek help on existing classes

Assignment 6: User Input(Command Line Argument)


Objective: Understand the command line arguments and Integer. parseInt method and its
working .
Problem Description: Create classes called UserInput. Create member variables which accept
values entered by the user through command line. The variable number will be the number
for which the multiplication table is to be generated and iterations will be the number till
which the multiplication table will be generated. Generate the multiplication table by
accepting input from user as mentioned in the description above.

public class UserInput {


public static void main(String[] args) {
int number, iterations;
number = Integer.parseInt(args[0]);
iterations = Integer.parseInt(args[1]);
/*write code to generate a multiplication table*/
}
}
Estimated time: 20 minutes
Summary of this assignment:

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 27 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

In this assignment, you have learnt


Taking input from user as arguments

Assignment 7:Command Line Argument


Objective: Understand command line arguments
Problem Description:
Enhance the Assignment 4 of Day 3 and do the necessary modification as mentioned below:

Student
-studentId : integer
-studentName:String
-residentialStatus:String
- feesPerMonth: long int
+Student()
+setStudentId(id:int):void
+setStudentName(firstName:String,lastName:String)
+setResidentialStatus(status:String)
+getStudentId():int
+getStudentName():String
+getResidentialStatus():String
+getFees():long int

Step 1: Through the command line argument get the value of studentId, studentName
residentialStaus, Semester fees and Hostel fees(only if the residential status is Hostelite)
Step 2: Set the value of the data members with the help of the setter method
Step 3: In the main method, create a reference variable student of type Student.
a. Using getter methods, display the student details
Step 4: Compile the program, fix the errors if any
Step 5: Execute the program and verify the output
Estimated time: 20 mins
Summary of this assignment:
In this assignment, you have learnt
How to implement command line argument and parseInt()method

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 28 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Assignment 8:Overloaded Methods


Objective: Understand method overloading
Problem Description:
Enhance the Assignment 7 and do the necessary modification as mentioned below:

Student
-studentId : integer
-studentType:char
-studentName:String

-residentialStatus:String

- feesPerMonth: double
+Student()
+Student(id,type,firstName,lastName)
+setStudentId(id:int):void
+setStudentType(type:char):void
+setStudentName(firstName:String,lastName:String)

+setResidentialStatus(status:String)
+getStudentId():int
+getStudentType():char
+getStudentName():String

+getResidentialStatus():String
+getFees():String

+calculateFees(semesterFees:double):void
+calculateFees(semesterFees:double,hostelFees:double):void

Step 1: Define the calculateFees methods as below:


calculateFees(double semesterFees){
feesPerMonth = semesterFees / 6.0;
}
calculateFees(double semesterFees,double hosterlFees){
feesPerMonth = semesterFees / 6.0;
feesPerMonth = feesPerMonth+ hostelFees;
}
Step 2: Define a main method

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 29 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

a. In the main method, create a reference variable student of type Student.


b. Create an object of type Student (id, type, firstName, lastName) and assign
it to reference variable named student.
c. Invoke setResidentialStatus method to set the residentialStatus as Day
Scholar or Hostelite
d. Check for the residential status, if residential status is equals to Day
Scholar,invoke calculateFees(double semesterFees) method otherwise,
invoke calculateFees(double semesterFees, double hosterlFees)
e. Using getter methods, display the student details
Step 3: Compile the program, fix the errors if any
Step 4: Execute the program and verify the output

Note:
Use boolean equalsIgnoreCase(String anotherString)
Method to check the content of the string objects for equality
Estimated time: 40 mins
Summary of this assignment:
In this assignment, you have learnt
How to implement method overloading

Self Review
What would be the output of the following programs?
1.
class StringEqual{
public static void main(String arg[]){
String name1,name2;
name1 = "God";
name2= name1;
if(name1 == name2){
System.out.println("Equal");
}
else{
System.out.println("Not Equal");
}
}
}

2.

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 30 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

class StringEqual{
public static void main(String arg[]){
String name1,name2;
name1 = new String("God");
name2= new String("God");
if(name1 == name2){
System.out.println("Equal");
}
else{
System.out.println("Not Equal");
}
}
}
3.
class StringEqual{
public static void main(String arg[]){
String name1,name2;
name1 = new String("God");
name2= new String("God");
if(name1.equals(name2)){
System.out.println("Equal");
}
else{
System.out.println("Not Equal");
}
}
}
4.
class StaticDemo
{
static int count=10;
StaticDemo(){
count++;
}
static void display(){
System.out.println(count);
}
static{
System.out.println("Static Block written Before Main");

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 31 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

}
public static void main(String args[]){
StaticDemo t1=new StaticDemo();
StaticDemo t2=new StaticDemo();
StaticDemo.display();
t2.display();
}
static{
System.out.println("Static Block written After Main");
}
}
5.
class MultiDimArray {
public static void main(String[] args) {
String[][] names = {{"Mrs.","Ms." , "Mr."},
{"Vani","Lesitha","Nishit","Meenakshi"}};
System.out.println(names[0][0] + names[1][0]);
System.out.println(names[0][2] + names[1][2]);
}
}
6.
class StaticDemo1{
private int num;
static void display(){
System.out.println(num);
}

public static void main(String args[]){


StaticDemo.display();
}
}
7.
What will be the output of the following:
public class thisSample {
public static void main(String[] args){
Square square =new Square();
square.display(5);
int area = square.calculateArea();

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 32 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

System.out.println("The area of the Square is

area);
}
}
public class Square {
int length;
void display(int length){
this.length=length;
}
int calculateArea(){
return(length*length);
}
}

Day 4 Assignments
Assignment 1: Inheritance
Objective: Understand the concept of Inheritance
Problem Description:
To implement the following class diagram
Student
-studentId : integer
-studentType:char
-studentName:String
-feesPerMonth: double
+Student()
+Student(id,type,firstName,lastName)
+setStudentId(id:integer):void
+setStudentType(type:char):void
+setStudentName(firstName:String,lastName:String)
+setFeesPerMonth(double)
+getStudentId():integer
+getStudentType():char
+getStudentName():String
+getStudentType():char
+getStudentName():String
+getFeesPerMonth():double
ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 33 of 68

" +

Infosys Technologies Limited

Object Oriented Programming using Java

Hostelite
-hostelName : String
-roomNumber : integer
+Hostelite()
+Hostelite(integer,char,String,double,String,integer)
+getHostelName():String
+getRoomNumber():integer
Step 1: Create a class Hostelite by reusing Student class.
Step 2: Implement all the methods specified in the Hostelite and store it in Hostelite.java
Step 3: In main method,
a. Create an object of type Hostelite by invoking the parameterized constructor
with the required parameters.
b. Display all the details of Hostelite (id, type, name, feesPerMonth, hostelName,
roomNo) by invoking appropriate getter methods.
Step 4: Compile the program, fix the errors if any
Step 5: Execute the program and verify the output
Estimated time: 25 mins
Summary of this assignment:
In this assignment, you have learnt
How to implement simple inheritance.

Assignment 2: protected Access Specifier


Objective: Understand the significance of protected access specifier in Inheritance.
Problem Description:
Modify the Assignment 1 of Day 4 with the following class diagram and steps

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 34 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Student
#studentId : integer
#studentType:char
#studentName:String
#feesPerMonth: double
+Student()
+Student(id,type,firstName,lastName)
+setStudentId(id:integer):void
+setStudentType(type:char):void
+setStudentName(firstName:String,lastName:String)
+setFeesPerMonth(double)
+getStudentId():integer
+getStudentType():char
+getStudentName():String
+getStudentType():char
+getStudentName():String
+getFeesPerMonth():double

Hostelite
-hostelName : String
-roomNumber : integer
+Hostelite()
+Hostelite(integer,char,String,double,String,integer)
+getHostelName():String
+getRoomNumber():integer

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 35 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Steps mentioned in Assignment 1 of Day4 have to be repeated with the following


modification.
Step 1: Modify the data members of the Student class from private to protected
Step 2: Hostelite class is derived from Student class
Step 3: In Hostelite () parameterized constructor, all the member variables (including Student
class members) have to be initialized with the corresponding parameters passed.
Step 4: Display the details.
Step 5: Compile the program, fix the errors if any
Step 6: Execute the program and verify the output
Estimated time: 15 mins
Summary of this assignment:
In this assignment, you have learnt
How to use the protected access specifier

Assignment 3: Method Overriding ,super keyword and Dynamic Binding


Objective: Understand the significance of super keyword and method overriding in
Inheritance.
Problem Description:
Modify the Assignment 2 of Day 4 with the following class diagram and steps

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 36 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Student
#studentId : integer
#studentType:char
#studentName:String
#feesPerMonth: double
+Student()
+Student(id,type,firstName,lastName)
+setStudentId(id:integer):void
+setStudentType(type:char):void
+setStudentName(firstName:String,lastName:String)
+setFeesPerMonth(double)
+getStudentId():integer
+getStudentType():char
+getStudentName():String
+getFeesPerMonth():double
+displayStudentDetails():void

Hostelite

DayScholar

-hostelName : String
-roomNumber : integer
+Hostelite()

-residentialAddress : String

+DayScholar()
+DayScholar(integer,char,String
,double,String)
+getResidentialAddress():String
+displayStudentDetails():void
CONFIDENTIAL
Version No. 1.2 37 of 68

+Hostelite(integer,char,String,double
,String,integer)

+getHostelName():String
+getRoomNumber():integer
ER/CORP/CRS/ LA1026
+displayStudentDetails():void

Infosys Technologies Limited

Object Oriented Programming using Java

Steps mentioned in Assignment 2 of Day4 have to be repeated with the following


modification.
Step 1: displayStudentDetails() method needs to be defined in Student class. This method
should display the student details.
Step 2: The method displayStudentDetails() needs to be overridden in Hotelite and
DayScholar classes which will display additional student information(hostelName and
roomNumber or residentialAddress).
Note:
Use super keyword to invoke the super class displayStudentDetails()

Step 3: In main method,


a. Create reference variable of type Student
b. Read the residential status of the student(from the command line argument
using String as described in earlier assignments- Hostelite or Dayscholar), if
(s)he is a hostelite then create object of type hostelite by invoking the
parameterized constructor and assign it to reference variable named
student otherwise, create object of type dayscholar by invoking the
corresponding parameterized constructor and assign it to reference
c. Invoke the corresponding displayDetails method and display the complete
student details
Step 4: Compile the program, fix the errors if any
Step 5: Execute the program and verify the output
Estimated time: 35mins

Assignment 4: super keyword


Objective: Understand the significance of super keyword
Problem Description:
Analyze the problem and Debug the code
Problem 1:

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 38 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

class Student{
protected int studentId;
protected char studentType;
protected String studentName;
protected int semesterFees;
protected int feesPerMonth;
Student(int studentId){
this.studentId=studentId;
}
Student(int studentId,char studentType,String studName,int
semFees){
super();
studentType=studentType;
studentName=studName;
semesterFees=semFees;
}
void displayDetails(){

}
}
class DayScholar extends Student{
private String residentialAddress;
DayScholar(int studentId,char studentType ,String
studName,int semFees,String residentialAddress){
this.residentialAddress=residentialAddress;
super(int studentId,char studentType,String
studName,int semFees);
}
void displayDetails(){
}
}
class CourseReg{
public static void main(String args[]){
DayScholar dayscholar = new DayScholar
(1001,'D',"Eugene",12000,"No 32/68
dayscholar.displayDetails();
}
}

Vijayanagar");

After fixing the errors, perform the following:


Step 1: In main method,

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 39 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

a. Create object of type Dayscholar by invoking the corresponding


constructor and assign it to reference variable dayscholar
b. Both the constructor of the Student class need to be invoked
c. Fill the displayDetails() of the both the class
d. dayscholar.displayDetails() should invoke both derived and base class
displayDetails()
Step 2: Compile the program, fix the errors if any
Step 3: Execute the program and verify the output
Estimated time: 40mins
Problem 2:
class CourseRegistration{
static protected int regId;
protected String courseName;
CourseRegistration(){
regId++;
}
CourseRegistration (String cName){
courseName=cName;
this();
}
public void displayDetails(){
System.out.println("Registration ID :"+regId);
System.out.println("CourseName :"+courseName);
}
}
class Student extends CourseRegistration{
protected int studentId;
protected char studentType;
protected String studentName;
private int semesterFees;
private int feesPerMonth;
Student(int studentId, String cName){
super(cName);
this.studentId=studentId;
}
Student(int studentId,char studentType,String studName,int
semFees,String cName){
super(cName);
studentType=studentType;

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 40 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

studentName=studName;
semesterFees=semFees;
}
}
class DayScholar extends Student{
private String residentialAddress;
DayScholar(int studentId,char studentType, String studName,
int semFees, String residentialAddress, String cName){
super(studentId,studentType,studName, semFees, cName);
this.residentialAddress=residentialAddress;
}
void displayDetails(){
//need to display the Details of the Student and
//DayScholar
}
}
class CourseReg{
public static void main(String args[]){
DayScholar dayscholar = new DayScholar
(1001,'D',"Eugene",12000,"No32/68 Vijayanagar","OOP");
dayscholar.displayDetails();
}
}
Debug the above code. Once done , follow the below stepsStep 1: In main method,
a. Create object of type Dayscholar by invoking the corresponding
constructor and assign it to reference variable dayscholar
b. Both the constructor of the Student class and CourseRegistration class
need to be invoked
c. Fill the displayDetails() of DayScholar class
d. dayscholar.displayDetails()
should
invoke
DayScholar
and
CourseRegistration displayDetails()
Step 2: Compile the program, fix the errors if any
Step 3: Execute the program and verify the output
Summary of this assignment:
In this assignment, you have learnt
Uses of super keyword
Estimated time: 25 mins

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 41 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Assignment 5: Constructor Invocation


Objective: Understand the order of constructor invocation
Problem Description:
Implement the following class diagram using Java.

Student
#studentId
#studentType
#studentName

: int
:char
:String

+Student()
+Student(int,char,String)

#postCourseId
#postCourseName
#postCoursefees

PostGradStudent
: int
:String
:int

+PostGradStudent(int,String,int,int,char,String)
+getpostCourseId():int
+getpostCourseName:String

DayScholar
-residentialAddress : String
+DayScholar(int,String,int,char,String,String)
+calculateFees():void
+getFees():int
Step 1:In the Student class

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 42 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Define constructor
o Student(): Used to increment the value of studentId each and every time
object is created. Hint : Use a static variable
o Student(sid,sType,sName): Used to initialize the instance variables
studentId,studentType,studentName and to invoke the constructor
Student()
Step 2:In the PostGradStudent class
Define constructor
o PostGradStudent(pCourseId,pCourseName,pCourseFees,
sid,sType,sName): Used to initialize the instance variables studentId ,
studentType studentName to invoke the constructor
Student(sid,sType,sName)
getter method
o Using getter methods, display the PostGraduation Student details.
Step 2:In the DayScholar class
Define constructor
DayScholar(pCourseId,pCourseName,pCourseFees, sid,sType,sName
,rAddress): Used initialize the instance variable residentialAddress and to
invoke the constructor PostGradStudent
(pCourseId,pCourseName,pCourseFees, sid,sType,sName)
calculateFees()
o calculate the fees as below.
calulateFees(){
fees= postCoursefees /6;
}
getter method
o Using getter methods, display the fees details.
Step 3:In the main method
Create
an
object
of
type
DayScholar
with
the
values(5,OOP,16000,1001,D,Manu,N0 32/3 Vijayanagar)and assign
it to reference variable named dayScholar
Call the corresponding methods
Step 4: Compile the program, fix the errors if any
Step 5: Execute the program and verify the output

Note:
super() can be used to invoke the base class constructor

Estimated time: 25 mins

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 43 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Summary of this assignment:


In this assignment, you have learnt
How to implement constructors
Constructor invocation

Assignment 6 : Dynamic Polymorphism


Objective: To understand the concept of Dynamic Polymorphism
Problem Description:
Analyze the problem and Debug the code and display the Result in the following
format
Student ID
:1001
Student Type :D
Student Name:Thomas
Residential Address:No 32/3 Vijayanagar
class Student {
protected int studentId;
protected char studentType;
protected String studentName;
public void setStudentId(int sId){
this.studentId=sId;
}
public void setStudentType(char sType){
this.studentType=sType;
}
public void setStudentName(String sName){
this.studentName=sName;
}
public void getDetails(){
System.out.println("Student ID :"+studentId);
System.out.println("Student Type :"+studentType);
}
}
class DayScholar extends Student{
private String residentialAddress;
public void setResAddress(String resAddress){
this.residentialAddress=resAddress;
}
public void getDetails(){

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 44 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

super.getDetails();
System.out.println("Student Name "+studentName);
System.out.println("Residential
Address"+residentialAddress);

}
}
class DynamicEx{
public static void main(String args[]){
Student dayScholar=new DayScholar();
dayScholar.setStudentId(1001);
dayScholar.setStudentType('D');
dayScholar.setStudentName("Thomas");
dayScholar.setResAddress();
dayScholar.getDetails();
}
}
Note:
A new method defined in the sub class cannot be called using the
super class reference

Estimated time: 15 mins


Summary of this assignment:
In this assignment, you have learnt
Dynamic polymorphism

Assignment 7:final keyword


Objective: Understand the significance of final keyword
Problem Description:
Reuse Assignment 6 of Day 4 to achieve the following:

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 45 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Student
#studentId : integer
#studentType:char
#studentName:String
# semesterFees: int
#feesPerMonth:int
+Student()
+setStudentId(id:integer):void
+setStudentType(type:char):void
+setStudentName(firstName:String,lastName:String)
+calculateFees():void
+displayDetail():void

DayScholar
-residentialAddress : String
+DayScholar()
+DayScholar(integer,char,String,doubl
e,String)
+displayDaySDetails():void

Step
Step
Step
Step

1: Make the Student class as specified in the class diagram


2: Data member semesterFees should be fixed as 12000
3:displayDetail() should not be used in any of its derived classes to display the details
4:calculateFees() method should be given as below :
void calculateFees(){

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 46 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

feesPerMonth = semesterFees / 6.0;


}
Step5:Make the class DayScholar in such a way that no other class should derive from
DayScholar
Step 6: Code the displayDaySDetails() to display the details of DayScholar
Step 7: In main method,
a. Create object of type DayScholar by invoking the corresponding constructor
and assign it to reference variable dayscholar
b. Set the value of all the data members with the help of setter method
c. Invoke the calculateFees method
d. Invoke the corresponding method to display the details of DayScholar and
Student
Step 6: Compile the program, fix the errors if any
Step 7: Execute the program and verify the output
Estimated time: 25 mins
Summary of this assignment:
In this assignment, you have learnt
Uses of final keyword

Assignment 8:Abstract Class


Objective: Understand the significance of super keyword and method overriding in
Inheritance.
Problem Description:
Modify the Assignment 3 of Day 4 with the following steps
Step 1: Make the Student class as abstract class
Step 2: Include an abstract method calculateFees(double)
Step 3: Define the method calculateFees(double) as follows in Dayscholar
class
void calculateFees(double semesterFees){
feesPerMonth = semesterFees / 6.0;
}
Step 4: Define the method calculateFees(double) as follows in Hostelite class
void calculateFees(double semesterFee){
feesPerMonth = semesterFees / 6.0;
// Add hostel fees Rs.1200
feesPerMonth = feesPerMonth+ 1200;
}

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 47 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Step 5: In main method,


a. Create reference variable of type Student
b. Read the residential status of the student(from the command line argument
using String as described in earlier assignments- Hostelite or Dayscholar), if
(s)he is a hostelite then create object of type hostelite by invoking the
parameterized constructor and assign it to reference variable named
student otherwise, create object of type dayscholar by invoking the
corresponding parameterized constructor and assign it to reference
c. Also, Invoke the corresponding calculateFees method and display the
complete student details
Step 6: Compile the program, fix the errors if any
Step 7: Execute the program and verify the output
Estimated time: 20 mins
Summary of this assignment:
In this assignment, you have learnt
abstract class and abstract method

Review
What would be output for the following programs? If there is an error in the program, analyze
it, fix it and execute it
1.
class Parent{
private int num;
public void setNum(int val){
num = val;
}
public int getNum(){
return num;
}
public void display(){
System.out.println("Number :"+num);
}
}
class Child extends Parent{
private int val;

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 48 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

public void setVal(int num){


val = num;
}
public int getVal(){
return val;
}
public void display(){
System.out.println("Number :"+num);
System.out.println("Value :"+val);
}
}
class CourseMgmt{
public static void main(String args[]){
Child child;
child = new Child();
child.setNum(100);
child.setVal(200);
child.display();
}
}
2.
class Parent{
private int num;
public void setNum(int val){
num = val;
}
public int getNum(){
return num;
}
public void display(){
System.out.println("Number :"+num);
}
}
class Child extends Parent{

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 49 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

private int val;


public void setVal(int num){
val = num;
}
public int getVal(){
return val;
}
public void display(){
super.display();
System.out.println("Value :"+val);
}
}
class CourseMgmt{
public static void main(String args[]){
Child child;
child = new Child();
child.setNum(100);
child.setVal(200);
child.display();
}
}

3.
class Animal {
public static void testClassMethod() {
System.out.println("The class method in Animal.");
}
public void testInstanceMethod() {
System.out.println("The instance method in Animal.");
}
}
class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The class method in Cat.");
}
public void testInstanceMethod() {

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 50 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

System.out.println("The instance method in Cat.");


}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testInstanceMethod();
}
}
4.
class Parent{
private int num;
Parent(int num){
this.num = num;
}
public int getNum(){
return num;
}

}
class Child extends Parent{
private int val;
Child(int num,int val){
// To invoke super class constructor
super(num);
this.val = val;
}
public int getVal(){
return val;
}
}
class CourseMgmt{
public static void main(String args[]){
Child child;

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 51 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

child = new Child(100,200);


System.out.println("Parent: Num:" + child.getNum());
System.out.println("Child: Val:" + child.getVal());

}
}
5.
public class ClassA {
public void methodOne(int i) {
}
public void methodTwo(int i) {
}
public static void methodThree(int i) {
}
public static void methodFour(int i) {
}
}
public class ClassB extends ClassA {
public static void methodOne(int i) {
}
public void methodTwo(int i) {
}
public void methodThree(int i) {
}
public static void methodFour(int i) {
}
}

Day 5 Assignments
Assignment 1: Package (Create, Compile & Execute )
Objective: Create and use Packages
Problem Description: To display student details using package program
Step1: Write the following program in a textpad

package courseregistration;

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 52 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

class Student {
protected int studentId;
protected char studentType;
protected String studentName;
public void setStudentId(int sId){
this.studentId=sId;
}
public void setStudentType(char sType){
this.studentType=sType;
}
public void setStudentName(String sName){
this.studentName=sName;
}
public void getDetails(){
System.out.println("Student ID :"+studentId);
System.out.println("Student Type :"+studentType);
System.out.println("Student Name :"+studentName);
}
}
class PackageEx{
public static void main(String args[]){
Student student=new Student();
student.setStudentId(1001);
student.setStudentType('D');
student.setStudentName("Thomas");
student.getDetails();
}
}

Step 2:Save the program using PackageEx.java

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 53 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Step 3: If the command prompt does not appear during the compilation or an execution do
the (Step4 & Step 5)
Step 4: Go to configure tab and select the Preferences-Tools-Compile Java and select
Prompt for parameters

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 54 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Step 5: In Tools-Run Java Application and select Prompt for parameters


Step 6: Give ctrl+1 for the compilation and give as below in the prompt
d . PackageEx.java
It will create a package in the current working directory

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 55 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Step 7:Give ctrl+2 for run the program and give as below in the prompt
courseregistration/PackageEx

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 56 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Estimated time: 25 mins


Summary of this assignment:
In this assignment, you have learnt
How to create, save , compile and execute the Package program using textpad

Assignment 2 : Access Specifier


Objective: Understand the use of various Access specifier
Problem Description:
Analyze the problem, Debug the code and display the result in the following format
Student Id:1001
Student Type:D
Student Name:Dinil

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 57 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

package studentpack;
public class Student {
int studentId;
private char studentType;
protected String studentName;
public void setStudentId(int sId){
this.studentId=sId;
}
public void setStudentType(char sType){
this.studentType=sType;
}
public void setStudentName(String sName){
this.studentName=sName;
}
}
package registrationpack;
class DayScholar extends Student{
private String residentialAddress;
public void setResAddress(String resAddress){
this.residentialAddress=resAddress;
}
public void getDetails(){
System.out.println("Student Id:"+studentId);
System.out.println("Student Type:"+studentType);
System.out.println("Student Name:"+studentName);
}
}
class Registration{
public static void main(String args[]){
DayScholar dayScholar=new DayScholar();
dayScholar.setStudentId(1001);
dayScholar.setStudentType('D');
dayScholar.setStudentName("Dinil");
dayScholar.getDetails();
}
}

Note: Compile the class Student separately in a package called courseregistration. There
is no error in this code. Compile the DayScholar and Registration classes separately in the
package registrationpack. There are some access related errors, analyse them, debug and
execute to get the output.

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 58 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Estimated time: 20 mins

Summary of this assignment:


In this assignment, you have learnt
Access specifier
package and import statement

Assignment 3:Interfaces
Objective: Understand the significance of interface

Problem Description:
Type the following code, debug the code and execute the same.
interface InterOne{
int varOne;
int varTwo=100;
void methodOne();
void methodTwo();
}
class Example implements InterOne{
void methodOne(){
varTwo=varTwo+10;
System.out.println("Value of varTwo:"+varTwo);
System.out.println("Good Morning");
}
public void methodTwo(){
System.out.println("Good Afternoon");
}
}
class DemoInterface{
public static void main(String args[]){
Example obj=new Example();
obj.methodOne();
obj.methodTwo();
}
}

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 59 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Estimated time: 15 mins


Summary of this assignment:
In this assignment, you have learnt
Interfaces

Assignment 4: UML Use Case Diagram


Objective: Analysis of the case study and design the Use Case Diagram.
Problem Description: Course Management System
A Course Management System needs to be developed for an engineering college. The college
wants an automated system to replace its manual system for purpose of allocation of students
to courses and lecturers to courses. There are around 10000 students and 500 faculty
members in the college. The engineering college provides graduation and post graduation in
the various branches of engineering.
In any branch, the entire duration is divided into semesters. Each semester includes various
courses. Students admitted into the college can apply for various courses. The courses are
elective in nature. The student needs to select two electives. The electives are offered from
5th semester onwards for graduate students and from 3rd semester onwards for the post
graduate students. The graduate students need to undergo a final year project in the fourth
year of engineering whereas the post graduate student undergoes a thesis submission in the
second year. The complete list of courses, lecturers and students is maintained in the college.
The list is constant and cannot be updated by the system. The automated system uses this list
for allocation of courses.
The lecturers can be categorized into full time lecturers and visiting members. The full time
lecturers have target days of course delivery and are paid salary every month. The visiting
members get paid per lecture basis and do not have any target days.
The system is used by the admin staff to register students admitted to college to the courses
they opted. The system needs to be authenticated with a login id and password. The system
would be used by the students to view the marks and the attendance details also. The system
is used by the HOD (Head of the department) to allocate courses to the lecturers. At the
beginning of the semester, the HOD will do the allocation of lecturers to the classes for his
department. The HOD may make changes in the allocation during the progress of the course.
The system maintains a history of all the lecturers who have handled the courses throughout
the semester .The lecturer will use the system to update the marks of the student (project,
assignment, internal test marks and the semester end examination marks). The lecturer will
also mark the attendance of the students through the system.
In addition to the above, the system also keeps track of the residential status of the student.
The student may be a host-elite or a day scholar. If (s)he is host-elite, the system will
maintain his / her hostels name, room number and the fees pertaining to the same.

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 60 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Note: This is the same case study provided in Day 1 assignment.

Step 1: Identify all the nouns i.e. the actors in the problem statement.
Step 2: Identify the activities i.e. the use cases. Connect the actors to the use cases.
Step 3: Identify the relationships.(Generalization, specialization, Includes)
Estimated time: 30 mins
Summary of this assignment:
In this assignment, you have learnt
How to analyze and design the Use case diagram for a given problem statement.

Assignment 5: UML Class Diagram


Objective: Analysis of the case study and design the class diagram.
Problem Description: Course Management System

Step 1: Identify all the nouns (type of objects or classes) in the case study given in previous
case study.
Step 2: Identify the commonalities between classes (Generalization) if it is obvious.
Step 3: Identify all the member variables and methods the class should have.
Step 4: Identify the member variables and methods (getter and setter methods for each and
every attribute) for the rest of the classes.
Step 5: Ensure that the class is fully independent of other classes and contains all the
attributes and methods necessary.
Step 6: Keep all data members private (-) or protected (#).
Step 7: The methods in class should completely abstract the functionality using
encapsulation. The methods in the class should not be a force fit of procedural code into a
class.
Step 8: Inherit and extend classes from the base class ONLY IF situation has scope for it. Shift
the commonalities among classes to the base class
Step 9: Define the Has-A and Uses-A relationship among classes
(Is-A has been defined already in previous step)

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 61 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Step 10: Keep the number of classes in your application under check (Do not create any
unnecessary classes)
Step 11: Review your design
Estimated time: 30 mins
Summary of this assignment:
In this assignment, you have learnt
How to analyze design a class diagram for the given problem statement.

Assignment 6: Case study of D-Rail Inc.


D-Rail Inc. is a metropolitan railway corporation operating in a large city and its suburbs. DRail has an ambitious plan to computerize its ticketing system. The IT department of D-Rail
has come up with an OO design for their ticketing system. Now, they require the design to be
validated for correctness.
The ticketing system addresses the needs of the metro rail service of D-Rail between the city
and its suburbs.
Requirements of the Ticketing System:
A Ticketing Clerk at one of the D-Rail counters can issue the following kinds of tickets to
commuters:
One Time ticket: Used for one way travel. It has to be used the same day it is issued.
Return ticket: Used for two way travel. Onward journey has to be done on the date of
issue. However, the return journey can be done any time within a week from the date of
issue.
Multi-use ticket: Used for traveling many times between an origin and destination
stations (onward or return). Multi-use tickets are available 10, 15 and 20 trips
denominations, which are also specified in the ticket. However the ticket has an expiry
date which is two months from the date of issue. Every time the ticket is used, one trip is
deducted.
All tickets have information on the origin and destination stations.
All the tickets issued are magnetic tickets which store the entire ticket information. This
information will be verified by the ticket reading machine at the entry points.
Step 1: Design the Class diagram
ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 62 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Step 2: Implement the Class diagram using Java


Estimated time: 30 mins
Summary of this assignment:
In this assignment, you have learnt
To understand a complex software system and design the Use Case and Class diagrams

Self review
What would be the output of the following programs?
1.
abstract class Animal {
abstract static void testClassMethod();
public void testInstanceMethod() {
System.out.println("The instance method in Animal.");
}
}
class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The class method in Cat.");
}
public void testInstanceMethod() {
System.out.println("The instance method in Cat.");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testInstanceMethod();
}
}
2.
interface Count {
short counter=0;
void countUp();
}
public class TestCount implements Count{
public static void main(String args[]){
TestCount test=new TestCount();
test.countUp();

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 63 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

}
public void countUp(){
for (int x=6;x>counter;x--,++counter){
System.out.println(" "+counter);
}
}
}
3.
interface ParentOne{
int pOne=1;
void printParentOne();
}
interface ParentTwo{
int pTwo=2;
void printParentTwo();
}
interface Child extends ParentOne, ParentTwo{
int child=3;
void printChild();
}
class InheritClass implements Child{
public void printParentOne(){
System.out.println(pOne);
}
public void printParentTwo(){
System.out.println(pTwo);
}
public void printChild(){
System.out.println(child);
}
}
class TestInterface{
public static void main(String args[]){
InheritClass inclass=new InheritClass();
inclass.printParentOne();
inclass.printParentTwo();
inclass.printChild();
}
}

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 64 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Case Study based Assignments


Case Study 1 Banking System
Day 2 Assignment 1: If-else condition
Objective: Understand control structures
Problem Description: To validate the account balance with reference to the
Intermediate Level Case study provided.
Step 1: Create a class called MinAccountBalValidation with the main method
Step 2: Create a class called Account with the following Class diagram
Account
-accAmount: int
-accNo:int
-custName: String
+getAccNo(): int
+getAmount(): int
+getCustName(): String
+setAccNo(): void
+setAmount(): void
+setCustName(): void

Step 3: Create an object of Account in the main method


Step 4: Set the amount to 5000 using the setter method
Step 5: Write the logic in the main method to check if the amount remaining is less
than 500. If so display a message The balance is below minimum value. Otherwise
display the existing balance.

Estimated time: 20 minutes


Summary of this assignment:
In this assignment, you have learnt
If else conditional statements

Case Study 2 Travel Management System


Day 2 Assignment 1: If-else condition

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 65 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Objective: Understand control structures


Problem Description: To validate the mode of travel with reference to the
Intermediate Level Case study provided.
Step 1: Create a class called Demo with the main method
Step 2: Create a class called Travel with the following Class diagram
Travel
-modeOfTravel: char
-noOfTickets:int
-amount:double
+getModeOfTravel (): char
+getNoOfTickets():int
+getAmount():double
+setAmount(double):void
+setModeOfTravel (char): void
+setNoOfTickets (int): void

Step 3: Create an object of Travel in the main method


Step 4: Set the mode of travel to F using the appropriate setter method
Step 5:Set the number of tickets to 3 using the appropriate setter method
Step 6: Write the logic in the main method to check the mode of travel. Set the
amount to paid as service charges as per the following table:
SE NO

MODE OF TRAVEL

SERVICE CHARGE PERTICKET

F(FOR FLIGHT)

500

T(FOR TRAIN)

100

B(FOR BUS)

50

The calculation of service charge is as follows:


Total Service charge =Service Charge perTicket * No. of Tickets
Estimated time: 20 minutes
Summary of this assignment:
In this assignment, you have learnt
If else conditional statements

Day 3 Assignment 2: Strings


Objective: To understand Strings

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 66 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Problem Description: To write the autogeneration of the ticket number based on


some criterion.
Step 1: Create a class called AutoGenerate with the main() method
Step 2: Write the logic to autogenerate the booking confirmation number as follows:
Format of Booking confirmation number:
Y

Here,
o YYY denotes travel company code 115
o X denotes mode of travel F-Flight, T-Train, B-Bus
o NNN denotes Flight/Train/Bus Code such as 101-105 for
flight,201-205 for Train and 301-305 for Bus
o ZZZZ denotes a unique code, which starts from 0001 in
a branch and increments sequentially by 1 for each
booking request
Step 3: Test the code by providing the following inputs to the fields as follows:
SE NO.

VALUES VALUES
FOR X
NNN

FOR VALUES
TO
BE
GENERATED FOR ZZZZ

CASE 1

102

0001

CASE 2

202

0002

CASE 3

304

0003

Note: The values for the different fields may be provided through the program itself
statically.
Estimated time: 20 minutes
Summary of this assignment:
In this assignment, you have learnt
If else conditional statements and Strings

Day 4 Assignment 3: Inheritance

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 67 of 68

Infosys Technologies Limited

Object Oriented Programming using Java

Objective: To understand the application of Inheritance concept


Problem Description: To identify situations where Inheritance is to be applied with
respect to Intermediate Case study provided.
Scenario 1: A user needs to provide details of the travel. The travel details include
mode of travel, source, and destination, date and time, ticket details and travel class
type. The type can be
 Flight-Economy( less expensive) or Business (upper or
executive class)
 Train-II Class (less expensive) or I Class(upper or executive
class)
 Bus Non-AC (ordinary) or AC (Air Conditioned)
The difference in the travel type amount to the difference in the fares only.
What will be the structure of the class and would Inheritance concept be applicable
to the mentioned scenario?
Scenario 2:
The taxi can be booked for difference kinds of tours. The tours are as follows:
o One way travel
o One day travel
o Package tour (more than one day travel)
The One way travel has a destination, the charges are calculated based on the
number of kilometers multiplied by two. The one day travel consists of starting time,
bus number, sight seeing locations and the charge is a lumpsum amount per person.
The package tour is a part of the stay in the hotel and contains the locations to be
visited, the travel schedule and the number of persons to travel.
What will be the class structure and would inheritance concept be applicable to this
scenario?
Estimated time: 20 minutes
Summary of this assignment:
In this assignment, you have learnt
Inheritance concept and its application

ER/CORP/CRS/ LA1026

CONFIDENTIAL

Version No. 1.2 68 of 68

You might also like