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

-Lab Manual for Advance Computer Programming

Lab-03
Inheritance and Association
Lab 3: Inheritance and Association

Table of Contents
1. Introduction 21

2. Activity Time boxing 23

3. Objective of the experiment 23

4. Concept Map 23

5. Homework before Lab 24


5.1 Problem Solution Modeling 24

6. Procedure& Tools 25
6.1 Tools 25
6.2 Setting-up JDK 1.7 [Expected time = 5mins] 25
6.2.1 Compile a Program 25
6.2.2 Run a Program 26
6.3 Walkthrough Task[Expected time = 30mins] 26
6.3.1 Implementing Inheritance 26
6.3.2 Implementing Association 27
6.3.3 Aggregation 28
6.3.4 Composition 31

7. Practice Tasks 33
7.1 Out comes 34
7.2 Testing 34

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

9. Evaluation criteria 34

10. Further Reading 35


10.1 Books 35
10.2 Slides 35

Department of Computer Page 20


Science,
C.U.S.T.
Lab 3: Inheritance and Association

Lab3: Object Oriented Relationships in Java

1. Introduction
You have learnt Java constructs, and object-oriented relationships in java. In this lab, you will
test the theory by implementing relationships. In OOP, various kinds of relationships (i.e.
inheritance, association, aggregation, composition) exist between various classes/objects. Java is
a strong supporter of OOP. Majority of the community know Java as Pure Object-Oriented
Language. Hence Java supports all of these relationships.

Inheritance is modeled as is-a relationship. Inheritance exists between classes and the main goal
of inheritance is to make objects that would represent specialized versions of generalized original
objects. For example, a car is-a vehicle, manager is-an employee etc. Inheritance is perhaps the
strongest way of reusing the features of a class i.e. attributes (data member) and behaviors
(functions). Following the OOP paradigm, Java allows the inheritance among classes so that the
characteristic(s) of one class is/are inherited by the other class(es). Hence, you can say that the
derived classes receive some their attributes from which the derived class is inherited. A major
advantage of inheritance is that it allows the reusability of code. Hence, the programmer can
simply create new (child) class(es) by using other (parent) class(es).

While considering the advantages of commonality between classes, in Java, you are able to
manage your classes in a way that a class (child/sub class) can extend the functionality by
inheriting the attributes and behaviors of an existing class commonly known as base/super class.
In simple words, you can define a class with certain data fields and/or member functions and
then identify other class(es) that can share these data fields and functions. In typical Java
inheritance, a class or classes known as derived class(es), subclass(es) or child class(es) is/are
able to inherit certain attributes and behavior of pre-existing class(es) that are known as base
class(es), superclass(es), or parent class(es). In practice, base classes are more general while
derived classes are specialized version of base classes and due to this reason, it is said that
inheritance maintains generalization and specialization. With inheritance, you can greatly save
the time and lessen the effort to write duplicate code.

Concerning inheritance syntax in Java, if you have a base class named person inherited by a
derived class named student then you have to write code in the following way

public class Person


{
//code statements go here
};
public class Student extends Person
{
//code statements go here
};

Department of Computer Page 21


Science,
C.U.S.T.
Lab 3: Inheritance and Association

In case of derived class’s object instantiation, In Java, unlike C++, all classes inherit from the
Object class directly or indirectly. Therefore, there is always a single inheritance tree of classes
in Java, and Object class is root of the tree. In Java, if we create a class that doesn’t inherit from
any class then it automatically inherits from Object class. In Java, methods are virtual by default.
Java doesn’t provide an inheritance specifier like public, protected or private. Therefore, we
cannot change the protection level of members of base class in Java, if some data member is
public or protected in base class then it remains public or protected in derived class. Java doesn’t
support multiple inheritance. A class cannot inherit from more than one class. A class can
implement multiple interfaces though.

Following Java example shows that Test class automatically inherits from Object class.

class Test {
// members of test
}
class Main {
public static void main(String[] args) {
Test t = new Test();
System.out.println("t is instanceof Object: " + (t instanceof Object));
}
}

The output of above code would be: t is instanceof Object: true

Association and aggregation/composition represent uses-a and has-a/have-a relationship,


respectively between objects. It is based on the object-oriented design where an object can
contain other object(s). Association specifies that objects of different kinds are connected with
each other and there exist no ownership and lifecycle dependency. In advance, aggregation and
composition are two types of association representing weak and strong (whole-part) relationship
between contained (whole) and owing (part) objects. Therefore, aggregation and composition are
other forms of code reusability along with inheritance. Aggregation is a special kind of
association represents ownership relationship between objects. Composition is special kind of
aggregation which represents ownership between objects along with the existence of life-cycle
dependency. A department-employees relationship is an example of aggregation whereas
university-departments relationship is an example of composition.

Following example explains the syntax for aggregation and composition in Java:

public class Battery{ }

public class Engine{ }

class Vehicle
{
Department of Computer Page 22
Science,
C.U.S.T.
Lab 3: Inheritance and Association

private Battery bat;


private Engine eng;
public Vehicle(Battery b)
{
bat = b;
eng = new Engine();
}
}

Above example shows that aggregation exists between battery and vehicle because of the
possession of ownership but not life-cycle dependency. On the contrary, composition exists
between vehicle and engine because of the possession of ownership and life-cycle dependency.

Regarding syntax, other details are given in the section 6.3.

Relevant Lecture Material

a) Revise Lecture No. 3 and 4


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

2. Activity Time boxing

Table 1: Activity Time Boxing


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

3. Objective of the experiment

 To get basic understanding of Object Oriented relations and how they are implemented
using Java.

4. Concept Map

This section provides you the overview of the concepts that will be discussed and implemented
in this lab.
Primarily two tasks are the part of each object-oriented design i.e. identification of object types
within the problem domain and relationship modeling between the existing object types. Three
kinds of relationships usually exist between identified objects i.e.
Department of Computer Page 23
Science,
C.U.S.T.
Lab 3: Inheritance and Association

is-a relationship (Inheritance)


uses-a relationship (Association)
has-a relationship (Aggregation, Composition)

The is-a relationship exhibits a relationship between an object of specific type to its general type.
For example, a bus is-a vehicle, an employee is-a person, circle is-a geometric shape etc. The is-
a relationship has been modeled in terms of inheritance that you have already studied in Lectures
15-18.

The uses-a relationship demonstrates that an object of one specific type uses an object of
different type to perform some activity. For example, a person uses-a wiper to wash bus window
pane, a teacher uses-a course to teach student, a cyclist uses-a pump in tire-pumping activity).
The uses-a relationship can be described as association between objects i.e. a teacher has
association with student through a specific course. Similarly, university has association with its
departments through administration. In simple words, association is a relationship between
objects where exists no ownership and each object has its own lifecycle. More specifically,
association are of two types i.e. aggregation and composition that represents has-a relationship
between objects.

The has-a relationship represents a classical ownership of whole-part relationship. Sometimes an


object of one type contains an object of type e.g. a university has-a number of departments and
ultimately a department has a number of professors, a bus has-an engine, a bike has-a set of
wheels etc. The has-a relationship can be modeled as aggregation and composition.

 Aggregation is type of association representing weak relationship. In aggregation,


contained object exists even after the release of an owning object. Hence, in aggregation,
there exists ownership without life-cycle dependency. For example, if a company no
longer exists even then employee of that will continue to exist.

 Composition is a special type of aggregation representing strong relationship in which


the life-cycle of the part is dependent on the whole. Existence of the part is directly
dependent on the existence of the whole. For example, the relationship between vehicle
and its engine. Engine is build and destroyed whenever a vehicle is build or destroyed,
respectively.

5. Homework before Lab

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

5.1 Problem Solution Modeling

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

Department of Computer Page 24


Science,
C.U.S.T.
Lab 3: Inheritance and Association

Draw a UML diagram for the following task. You are required to bring this design with you
and submit to your lab instructor.

5.1.1 Problem description:

Design a class named Person and its two derived classes named Student and Teacher. There is
another class that contains many students and a teacher.

The Person class has


Attributes i.e. name, age, phone number, and e-mail address
Behavior i.e. work something

The Student class has


Attributes i.e. registration ID, department, number of completed credit hours
Behavior i.e. pay course registration fee

The class named Teacher contains the following


Attributes i.e. staff ID, salary
Behavior i.e. teach course(s)

The class named Course contains the following


Attributes i.e. Teachers List, Student List
Behavior i.e. have classes.

Draw UML diagram for each class and show inheritance relationship among all classes.

6. Procedure& Tools

6.1 Tools

Java Development Kit (JDK) 1.7

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

Refer to Lab 1 sec 6.2.

6.2.1 Compile a Program

Use the following command to compile the program.

javac Interface.java

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

Department of Computer Page 25


Science,
C.U.S.T.
Lab 3: Inheritance and Association

Now you will need JVM to run the program.

6.2.2 Run a Program

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

java DriverClass

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

6.3 Walkthrough Task[Expected time = 30mins]

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

6.3.1 Implementing Inheritance


Write the following code:
class Base {
    private int b;
    Base(int x) {
        b = x;
        System.out.println("Base constructor called");
    }               
}
  
class Derived extends Base {
    private int d;
    Derived(int x, int y) {
        // Calling parent class parameterized constructor
      // Call to parent constructor must be the first line in a Derived class
        
super(x);
        d = y;
        System.out.println("Derived constructor called");
    }                   
}
  
class Main{
    public static void main(String[] args) {
      Derived obj = new Derived(1, 2);
    }

6.3.2 Implementing Association


The following Java program to illustrate the concept of Association.

Department of Computer Page 26


Science,
C.U.S.T.
Lab 3: Inheritance and Association

import java.io.*;

// class bank
class Bank
{
private String name;

// bank name
Bank(String name)
{
this.name = name;
}

public String getBankName()


{
return this.name;
}
}

// employee class
class Employee
{
private String name;

// employee name
Employee(String name)
{
this.name = name;
}

public String getEmployeeName()


{
return this.name;
}
}

// Association between both the


// classes in main method
class Association
{
public static void main (String[] args)
{
Bank bank = new Bank("Axis");
Employee emp = new Employee("Neha");

Department of Computer Page 27


Science,
C.U.S.T.
Lab 3: Inheritance and Association

System.out.println(emp.getEmployeeName() +
" is employee of " + bank.getBankName());
}
}

Output:

Neha is employee of Axis

In above example two separate classes Bank and Employee are associated through their Objects.
Bank can have many employees, So it is a one-to-many relationship.

6.3.3 Aggregation
It is a special form of Association where, It represents Has-A relationship. It is a unidirectional
association i.e. a one way relationship.

For example, department can have students but vice versa is not possible and thus unidirectional
in nature.

In Aggregation, both the entries can survive individually which means ending one entity will not
effect the other entity

Following is a Java program to illustrate the concept of Aggregation.

import java.io.*;
import java.util.*;

// student class
class Student
{
String name;
int id ;
String dept;

Student(String name, int id, String dept)


{

this.name = name;
this.id = id;
this.dept = dept;

}
}

Department of Computer Page 28


Science,
C.U.S.T.
Lab 3: Inheritance and Association

/* Department class contains list of student


Objects. It is associated with student
class through its Object(s). */
class Department
{

String name;
private List<Student> students;
Department(String name, List<Student> students)
{

this.name = name;
this.students = students;

public List<Student> getStudents()


{
return students;
}
}

/* Institute class contains list of Department


Objects. It is asoociated with Department
class through its Object(s).*/
class Institute
{

String instituteName;
private List<Department> departments;

Institute(String instituteName, List<Department> departments)


{
this.instituteName = instituteName;
this.departments = departments;
}

// count total students of all departments


// in a given institute
public int getTotalStudentsInInstitute()
{
int noOfStudents = 0;
List<Student> students;
for(Department dept : departments)
{
Department of Computer Page 29
Science,
C.U.S.T.
Lab 3: Inheritance and Association

students = dept.getStudents();
for(Student s : students)
{
noOfStudents++;
}
}
return noOfStudents;
}

// main method
class GFG
{
public static void main (String[] args)
{
Student s1 = new Student("Mia", 1, "CSE");
Student s2 = new Student("Priya", 2, "CSE");
Student s3 = new Student("John", 1, "EE");
Student s4 = new Student("Rahul", 2, "EE");

// making a List of
// CSE Students.
List <Student> cse_students = new ArrayList<Student>();
cse_students.add(s1);
cse_students.add(s2);

// making a List of
// EE Students
List <Student> ee_students = new ArrayList<Student>();
ee_students.add(s3);
ee_students.add(s4);

Department CSE = new Department("CSE", cse_students);


Department EE = new Department("EE", ee_students);

List <Department> departments = new ArrayList<Department>();


departments.add(CSE);
departments.add(EE);

// creating an instance of Institute.


Institute institute = new Institute("BITS", departments);

System.out.print("Total students in institute: ");


System.out.print(institute.getTotalStudentsInInstitute());
Department of Computer Page 30
Science,
C.U.S.T.
Lab 3: Inheritance and Association

}
}

Output:

Total students in institute: 4

In this example, there is an Institute which has no. of departments like CSE, EE. Every
department has no. of students. So, we make a Institute class which has a reference to Object or
no. of Objects (i.e. List of Objects) of the Department class. That means Institute class is
associated with Department class through its Object(s). And Department class has also a
reference to Object or Objects (i.e. List of Objects) of Student class means it is associated with
Student class through its Object(s). It represents a Has-A relationship.

6.3.4 Composition
Composition is a restricted form of Aggregation in which two entities are highly dependent on
each other. It represents part-of relationship. In composition, both the entities are dependent on
each other. When there is a composition between two entities, the composed object cannot exist
without the other entity.

Let’s take example of Library.

import java.io.*;
import java.util.*;

// class book
class Book
{

public String title;


public String author;

Book(String title, String author)


{

this.title = title;
this.author = author;
}
}

// Libary class contains


// list of books.
class Library
{
Department of Computer Page 31
Science,
C.U.S.T.
Lab 3: Inheritance and Association

// reference to refer to list of books.


private final List<Book> books;

Library (List<Book> books)


{
this.books = books;
}

public List<Book> getTotalBooksInLibrary(){

return books;
}

// main class
class GFG
{
public static void main (String[] args)
{

// Creating the Objects of Book class.


Book b1 = new Book("EffectiveJ Java", "Joshua Bloch");
Book b2 = new Book("Thinking in Java", "Bruce Eckel");
Book b3 = new Book("Java: The Complete Reference", "Herbert Schildt");

// Creating the list which contains the


// no. of books.
List<Book> books = new ArrayList<Book>();
books.add(b1);
books.add(b2);
books.add(b3);

Library library = new Library(books);

List<Book> bks = library.getTotalBooksInLibrary();


for(Book bk : bks){

System.out.println("Title : " + bk.title + " and "


+" Author : " + bk.author);
}
}
}

Department of Computer Page 32


Science,
C.U.S.T.
Lab 3: Inheritance and Association

Output

Title : EffectiveJ Java and Author : Joshua Bloch


Title : Thinking in Java and Author : Bruce Eckel
Title : Java: The Complete Reference and Author : Herbert Schildt

In above example a library can have no. of books on same or different subjects. So, If Library
gets destroyed then All books within that particular library will be destroyed. i.e. book can not
exist without library. That’s why it is composition.

7. Practice Tasks

This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the
following folder:
\\dataserver\assignments$\OOP\Lab123
Practice Task 1 [Expected Time = 80 mins] 
Consider six classes i.e. Person, Professor, Researcher, Department, Laboratory, and
University having following specifications.

Class University has


Two attributes of type string i.e. universityName and location
An attribute named dept of type Department

Class Department has


Two attributes i.e. deptID, deptName
A two-argument constructor to initialize data fields with user-defined values
A member function display() to show all attribute values

Class Laboratory contains


Two attributes i.e. labID and experimentNo
A two-argument constructor to initialize data member with user-defined values

Class Person has


Two attributes i.e. name and age
A parameterized constructor to initialize attributes with user-defined values
A member function display() to show its attribute values

Class Professor is derived from class Person and has


A data field named profName of type string
A data field named dept of type Department
A two-argument constructor to initialize both attributes of user-defined values

Department of Computer Page 33


Science,
C.U.S.T.
Lab 3: Inheritance and Association

Class Researcher is derived from class Professor and has


An additional attribute named lab of type Laboratory
A constructor to initialize lab with user-defined value

 Draw UML diagram for each class and show inheritance, aggregation, and composition
relationship between these classes.
 Implement all these classes while illustrating the concept of aggregation and composition in
terms of ownership and life-cycle.

7.1 Out comes

After completing this lab, student will be able to implement the concepts of association,
aggregation, and composition in terms of ownership and life cycle of associated objects.

7.2 Testing

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

For Practice Task 1, Lab instructor must verify the implementation and required relationships
among all classes and objects. In addition, it is required to confirm that code has clearly
elaborated the concept of aggregation and composition in terms of ownership and life cycle.

Table 3: Practice Tasks Confirmation

Practice Tasks Confirmation Comments


T1

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

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

9. Evaluation criteria

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

Table 3: Evaluation of the Lab


Sr. No. Task No Description Marks
1 4 Problem Modeling 20
2 6 Procedures and Tools 10

Department of Computer Page 34


Science,
C.U.S.T.
Lab 3: Inheritance and Association

3 7 Practice tasks and Testing 35


4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

10. Further Reading

This section provides the references to further polish your skills.

10.1 Books

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

10.2 Slides

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

Department of Computer Page 35


Science,
C.U.S.T.

You might also like