Вы находитесь на странице: 1из 6

Course Code: CS221L Object Oriented Programming

Lab 08: Abstract Classes and Polymorphism

The ArrayList class implements a grow-able List of objects. It is better to use ArrayList class, rather than
creating your own linked-list structure.

Need to import class : java.util.ArrayList

// Create an instance of class ArrayList


ArrayList <String> array=new ArrayList<String>();

// or suggest an initial ArrayList size


ArrayList <String> array=new ArrayList<String>(10);

Some common methods for ArrayList Class:

Return type Method Explanation


boolean add(Object element) Appends the specified element to the end
of this list.
void add(int index, Object element) Inserts the specified element at the
specified position in this list. Shifts the
element currently at that position (if any)
and any subsequent elements to the right
(adds one to their indices).

object remove(int index) Removes the element at the specified


position in this list. Shifts any subsequent
elements to the left (subtracts one from
their indices).

object get(int index) Returns the element at the specified


position in this list.

object set(int index,Object element) Replaces the element at the specified


position in this list with the specified
element.

int Size() This method returns the number of


elements in this list.
boolean isEmpty() This method returns true if this list
contains no elements.

Centre for Advanced Studies in Engineering


Course Code: CS221L Object Oriented Programming
Lab 08: Abstract Classes and Polymorphism

ArrayList Iterator:
Used to loop through all the elements of ArrayList (Alternative of for and for-each loop to traverse the
ArrayList)

//first you have to declare the list


ArrayList<Object> listofObject=new ArrayList<Object> ();

//then declare its iterator


Iterator<Object> iterator=listofObject.iterator();

Some common methods for Iterator:

Return type Method Explanation


boolean hasNext() Returns true if the iteration has more
elements. (In other words, returns true
if next () would return an element
rather than throwing an exception.)

Object next() Returns the next element in the iteration.

Example code

import java.util.ArrayList;
import java.util.Iterator;

public class TempClass {

public static void main(String[] args) {

ArrayList<String> stringArrayList=new ArrayList<String>();

stringArrayList.add("Adding");
stringArrayList.add("String");
stringArrayList.add(1,"a");

Iterator<String> arrayIterator= stringArrayList.iterator();


while(arrayIterator.hasNext())
{
String s= arrayIterator.next();
System.out.println(s);
}

} }
Output
Centre for Advanced Studies in Engineering
Course Code: CS221L Object Oriented Programming
Lab 08: Abstract Classes and Polymorphism

1. Adding
2. a
3. String

Abstract Classes:

An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract
classes cannot be instantiated, but they can be sub-classed.

An abstract method is a method that is declared without an implementation (without braces, and followed by a
semicolon), like this:

abstract void moveTo(double deltaX, double deltaY);

If a class includes abstract methods, then the class itself must be declared abstract, as in:

public abstract class GraphicObject {


// declare fields
// declare non-abstract methods
abstract void draw();
}

When an abstract class is sub-classed, the subclass usually provides implementations for all of the abstract
methods in its parent class. However, if it does not, then the subclass must also be declared abstract.

Example

public class Main{


public static void main(String args[]){
TwoWheeler test = new Honda();
test.run();
}
}
abstract class TwoWheeler {
public abstract void run();
}
class Honda extends TwoWheeler{
public void run(){
System.out.println("Running..");
}
}

Centre for Advanced Studies in Engineering


Course Code: CS221L Object Oriented Programming
Lab 08: Abstract Classes and Polymorphism

Polymorphism:
Polymorphism is a generic term that means 'many shapes'. More precisely Polymorphism means the ability to
request the same operations be performed by a wide range of different types of things. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

Task 1:
In this task you are going to implement the concept of polymorphism.
 Create a class named Person
o Person Class should be abstract.
o A getName() method that is abstract as well.
 Create a class named Student
o Student inherits the Person Class.
o Override getName() method.
 Create a class named Professor
o Professor inherits the Person Class.
o Override getName() method.

Person

getName():String

Student Professor

+getName():String +getName():String

TestClass

+ printName(person : Person)
+ main(args : String [])

 In the TestClass, you have to create two method:


o A printName() method , which receives an argument of type Person and calls getName()
method to print the name according to their respective references.
o A main method, in which you create object of a Student and a Teacher using default
constructor call and call printName() method with reference of Student and Teacher.
Centre for Advanced Studies in Engineering
Course Code: CS221L Object Oriented Programming
Lab 08: Abstract Classes and Polymorphism

The name person in the printName(Person) method may denote instances of different classes (namely
of Student and of Professor). This works since both inherit from the Person class which defines
the getName() method. The compiler makes sure that all subclasses have a getName() method.

Task 2:
Payroll System using Polymorphism:

A company pays its employees monthly. The employees are of two types:
 A part time employee, working on hourly basis.
 A full time employee, a permanent employee having fixed salary per month.

Employee

Visiting Employee Permanent Employee

Now you have to create the following classes in order to capture the above scenario.

Employee class:
1. Make this class abstract.
2. Data Members are: Name, ID, Gender, and Salary, declare Salary as protected.
3. Default constructor.
4. Overloaded constructor with arguments Name, ID, Gender.
5. Implement toString() method that returns a string of all data members.
6. Write a calculateSalary() function and make it abstract.

Visiting Employee class extends Employee Class:


Visiting employees are paid by the pay Rate. Salary Calculation will be done on the basis of working hours and
pay rate.

1. The Visiting Employee class has additional data members WorkingHours, PayRate.
2. Default Constructor.
3. Overloaded constructor with arguments Name, ID, Gender, PayRate, WorkingHour and call to the
Employee constructor using super keyword.
4. Getters and Setters.
5. Implement toString() method that returns a string of all data members of superclass and subclass.

Centre for Advanced Studies in Engineering


Course Code: CS221L Object Oriented Programming
Lab 08: Abstract Classes and Polymorphism

6. Override calculateSalary() method (which was declared abstract in Employee Class) that will set the
Salary on the basis of hourly system. e.g. if pay rate is 50 and working hours are 20 then salary will be
(20*50).

Permanent Employee class extends Employee Class:


Permanent employees are paid a fixed monthly salary. For 17 grade employee salary will be 30,000, for 18
grade employee salaries will be 32,000 and for 19 grade employee salary will be 34,000. 5% tax will be cut
from permanent employee’s salary.
1. The Full time Employee class has an additional argument Grade (e.g 17 grade or 20 grade etc.)
2. Getters and setters.
3. Default Constructor.
4. Overloaded constructor with arguments Name, ID, Gender, Grade and call to the employee constructor
using super keyword.
5. Implement toString() method that returns a string of all data members of superclass and subclass.
6. Override calculateSalary()method (which was declared abstract in Employee Class) that will set the
Salary on the following basis:
a. For 17 grade employee salary will be 30,000, for 18 grade employee salary will be 32,000 and
for 19 grade employee salary will be 34,000.
b. 5% tax will be cut from permanent employee’s salary.
c. Example, if Grade is 17 then Salary after tax deduction is 30,000 – (30,000 * 5%)

Main Function:

Create 3 permanent and 2 visiting employees.


1. Store them into ArrayList<Employee > using the add() method
2. Iterate through the ArrayList using the iterator and
o Calculate their salaries.
o Display all employees by calling toString().

Centre for Advanced Studies in Engineering

Вам также может понравиться