5 Ood

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

Dr.

Raj Singh
Software Architecture

Object and Class

Object Oriented Principles

OOP Example

Terms to Remember

2
A high level structure of a software system.

Rules, heuristics and patterns for system


design.

Partitioning the system into discrete pieces

used to create interfaces between


the pieces
Techniques manage overall structure and flow
interface the system to its
environment

Defines appropriate use of development and


delivery techniques and tools.

3
Controls complexity

Enforces best practices

Provides consistency and uniformity

Increases predictability

Enables reusability

4
5
A paradigm that represents concepts as "objects" that have attributes that
describe the object and associated procedures known as methods.

Objects, which are usually instances of classes, are used to interact with
one another to design applications.

Objective-C, Smalltalk, Java and C# are examples of object-oriented


programming languages.

6
An object can be considered as a "thing" that can perform
a set of related activities.

The set of activities that the object performs defines the


object's behavior.

In pure OOP terms an object is an instance of a class.

7
§ A class is a representation of a type of object.

§ It describe the details of an object.


§ Class is composed of three things: name, attributes, and operations.

public class Student {


private String name;

private void method1(){

}

}
Student objectStudent = new Student();
• student object, named objectStudent, is created out of the Student class.
8
SRP - The Single Responsibility Principle A class should have one, and only one, reason to change.

You should be able to extend a classes behavior, without


OCP - The Open Closed Principle modifying it.

LSP - The Liskov Substitution Principle Derived classes must be substitutable for their base classes.

DIP - The Dependency Inversion Principle Depend on abstractions, not on concretions.

ISP - The Interface Segregation Principle Make fine grained interfaces that are client specific.

9
Encapsulation information hiding

define, don’t
Abstraction implement

Inheritance extensibility

one object many


Polymorphism shapes

10
Association is a (*a*) Aggregation, a special Composition can be Aggregation is a special
relationship between two type of an association, is recognized as a special kind of an association
classes, where one class the (*the*) relationship type of an aggregation. and composition is a
use another between two classes. special kind of an
aggregation.
Association is non-directional, Association àAggregation
aggregation insists a direction. àComposition

11
University aggregate Chancellor. University can
exist without a Chancellor.

Faculties cannot exist without the University.

The life time of a Faculty is attached with the life time


of the University .

University is composed of Faculties.

12
Abstraction is an emphasis on the idea, qualities and properties rather
than the particulars.

“What” rather than “How”

Generalization is the broadening of application to encompass a larger


domain of objects of the same or different type.

Abstraction and generalization are often used together.

13
Software Reuse an existing
class and it’s
reusability behavior

Create new class Absorb existing


class’s data and
from an existing behaviors
Enhance with new
class capabilities

More specialized
Subclass extends group of objects
Behaviors
superclass inherited from
superclass

14
Classes that are too general to create real objects

Used only as abstract superclasses for concrete


subclasses and to declare reference variables

Many inheritance hierarchies have abstract


superclasses occupying the top few levels

Use to declare a class abstract


Keyword abstract Also use to declare a method
abstract

Abstract classes normally contain one or more


abstract methods

All concrete subclasses must override all


inherited abstract methods
15
Interfaces are used to separate design from coding as class
method headers are specified but not their bodies.

Interfaces are similar to abstract classes but all methods


are abstract and all properties are static final.

Interfaces can be inherited (i.e.. you can have a sub-


interface).

An interface is used to tie elements of several classes


together.

This allows compilation and parameter consistency testing


prior to the coding phase.

Interfaces are also used to set up unit testing frameworks.

16
Facilitates adding new classes to a system
with minimal modifications

When a program invokes a method through


a superclass variable, the correct subclass
version of the method is called, based on
the type of the reference stored in the
superclass variable

The same method name and signature can


cause different actions to occur, depending
on the type of object on which the method is
invoked

17
More than one
method in a class with

Overloading
same name different
signature.
Does not depend on
return type.

Method in a subclass
Overriding with same name and
return type.

Also known as late


binding
Calls to overridden
Dynamic Binding methods are resolved
at execution time,
based on the type of
object referenced

18
19
1 // Employee.java
2 // Employee abstract superclass.
3
4 public abstract class Employee
Declare abstract class Employee
5 {
6 private String firstName;
Attributes common to all employees
7 private String lastName;
8 private String socialSecurityNumber;
9 public Employee( String first, String last){
10 firstName = first;
11 lastName = last; Method Overloading
12 }
13 public Employee( String first, String last, String ssn){
14 firstName = first;
15 lastName = last;
16 socialSecurityNumber = ssn;
17 } // end three-argument Employee constructor

20
18 // set first name
19 public void setFirstName( String first )
20 {
21 firstName = first;
22 } // end method setFirstName
23
24 // return first name
25 public String getFirstName()
26 {
27 return firstName;
28 } // end method getFirstName
29
30 // set last name
31 public void setLastName( String last )
32 {
33 lastName = last;
34 } // end method setLastName
35
36 // return last name
37 public String getLastName()
38 {
39 return lastName;
40 } // end method getLastName
21
41
42 // set social security number
43 public void setSocialSecurityNumber( String ssn )
44 {
45 socialSecurityNumber = ssn; // should validate
46 } // end method setSocialSecurityNumber
47
48 // return social security number
49 public String getSocialSecurityNumber()
50 {
51 return socialSecurityNumber;
52 } // end method getSocialSecurityNumber
53
54 // return String representation of Employee object
55 public String toString()
56 {
57 return String.format( "%s %s\nsocial security number: %s",
58 getFirstName(), getLastName(), getSocialSecurityNumber() );
59 } // end method toString
60
61 // abstract method overridden by subclasses
62 public abstract double earnings(); // no implementation here
63 } // end abstract class Employee

abstract method earnings 22


has no implementation
1 // SalariedEmployee.java
2 // SalariedEmployee class extends Employee.
3
4 public class SalariedEmployee extends Employee Class SalariedEmployee
5 {
extends class Employee
6 private double weeklySalary;
7
8 // four-argument constructor
9 public SalariedEmployee( String first, String last, String ssn,
10 double salary ) Call superclass constructor
11 {
12 super( first, last, ssn ); // pass to Employee constructor
13 setWeeklySalary( salary ); // validate and store salary
14 } // end four-argument SalariedEmployee constructor
15 Call setWeeklySalary method
16 // set salary
17 public void setWeeklySalary( double salary )
18 {
19 weeklySalary = salary < 0.0 ? 0.0 : salary; Validate and set weekly salary value
20 } // end method setWeeklySalary
21 23
22 // return salary
23 public double getWeeklySalary()
24 {
25 return weeklySalary;
26 } // end method getWeeklySalary
27
28 // calculate earnings; override abstract method earnings in Employee
29 public double earnings()
30 {
31 return getWeeklySalary(); Override earnings method so
32 } // end method earnings
SalariedEmployee can be concrete
33
34 // return String representation of SalariedEmployee object
35 public String toString()
36 { Override toString method
37 return String.format( "salaried employee: %s\n%s: $%,.2f",
38 super.toString(), "weekly salary", getWeeklySalary() );
39 } // end method toString
40 } // end class SalariedEmployee

Call superclass’s version of toString 24


1 // HourlyEmployee.java
2 // HourlyEmployee class extends Employee.
3
4 public class HourlyEmployee extends Employee
Class HourlyEmployee extends class
5 { Employee
6 private double wage; // wage per hour
7 private double hours; // hours worked for week
8
9 // five-argument constructor
10 public HourlyEmployee( String first, String last, String ssn,
11 double hourlyWage, double hoursWorked )
12 { Call superclass constructor
13 super( first, last, ssn );
14 setWage( hourlyWage ); // validate hourly wage
15 setHours( hoursWorked ); // validate hours worked
16 } // end five-argument HourlyEmployee constructor
17
18 // set wage
Validate and set hourly wage value
19 public void setWage( double hourlyWage )
20 {
21 wage = ( hourlyWage < 0.0 ) ? 0.0 : hourlyWage;
22 } // end method setWage
23
24 // return wage
25 public double getWage()
26 {
27 return wage;
28 } // end method getWage
29

25
30 // set hours worked
31 public void setHours( double hoursWorked )
32 {
33 hours = ( ( hoursWorked >= 0.0 ) && ( hoursWorked <= 168.0 ) ) ?
34 hoursWorked : 0.0;
35 } // end method setHours
36
37 // return hours worked Validate and set hours worked value
38 public double getHours()
39 {
40 return hours;
41 } // end method getHours
42
43 // calculate earnings; override abstract method earnings in Employee
44 public double earnings()
45 { Override earnings method so
46 if ( getHours() <= 40 ) // no overtime
47 return getWage() * getHours();
HourlyEmployee can be concrete
48 else
49 return 40 * getWage() + ( gethours() - 40 ) * getWage() * 1.5;
50 } // end method earnings
51
52 // return String representation of HourlyEmployee object
53 public String toString()
Override toString method
54 {
55 return String.format( "hourly employee: %s\n%s: $%,.2f; %s: %,.2f",
56 super.toString(), "hourly wage", getWage(),
57 "hours worked", getHours() );
58 } // end method toString
Call superclass’s toString method
26
59 } // end class HourlyEmployee

26
1 // CommissionEmployee.java
2 // CommissionEmployee class extends Employee.
3
4 public class CommissionEmployee extends Employee Class CommissionEmployee
5 {
extends class Employee
6 private double grossSales; // gross weekly sales
7 private double commissionRate; // commission percentage
8
9 // five-argument constructor
10 public CommissionEmployee( String first, String last, String ssn,
11 double sales, double rate )
12 {
13 super( first, last, ssn );
14 setGrossSales( sales );
Call superclass constructor
15 setCommissionRate( rate );
16 } // end five-argument CommissionEmployee constructor
17
18 // set commission rate
19 public void setCommissionRate( double rate )
20 {
21 commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;
22 } // end method setCommissionRate
23

Validate and set commission rate value

27
27
24 // return commission rate
25 public double getCommissionRate()
26 {
27 return commissionRate;
28 } // end method getCommissionRate
29
30 // set gross sales amount
31 public void setGrossSales( double sales )
32 {
33 grossSales = ( sales < 0.0 ) ? 0.0 : sales;
34 } // end method setGrossSales
35
36 // return gross sales amount Validate and set the gross sales value
37 public double getGrossSales()
38 {
39 return grossSales;
40 } // end method getGrossSales
41

28
28
42 // calculate earnings; override abstract method earnings in Employee
43 public double earnings()
44 { Override earnings method so
45 return getCommissionRate() * getGrossSales(); CommissionEmployee can be concrete
46 } // end method earnings
47
48 // return String representation of CommissionEmployee object
49 public String toString()
50 {
Override toString method
51 return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f",
52 "commission employee", super.toString(),
53 "gross sales", getGrossSales(),
54 "commission rate", getCommissionRate() );
55 } // end method toString
Call superclass’s toString method
56 } // end class CommissionEmployee

29
29
1 // BasePlusCommissionEmployee.java
2
Class BasePlusCommissionEmployee extends
// BasePlusCommissionEmployee class extends CommissionEmployee.
3 class CommissionEmployee
4 public class BasePlusCommissionEmployee extends CommissionEmployee
5 {
6 private double baseSalary; // base salary per week
7
8 // six-argument constructor
9 public BasePlusCommissionEmployee( String first, String last,
10 String ssn, double sales, double rate, double salary )
11 {
12 super( first, last, ssn, sales, rate ); Call superclass constructor
13 setBaseSalary( salary ); // validate and store base salary
14 } // end six-argument BasePlusCommissionEmployee constructor
15
16 // set base salary
17 public void setBaseSalary( double salary )
18 {
19 baseSalary = ( salary < 0.0 ) ? 0.0 : salary; // non-negative
20 } // end method setBaseSalary
21

Validate and set base salary value

30
30
22 // return base salary
23 public double getBaseSalary()
24 {
25 return baseSalary;
26 } // end method getBaseSalary
27
28 // calculate earnings; override method earnings in CommissionEmployee
29 public double earnings()
30 { Override earnings method
31 return getBaseSalary() + super.earnings();
32 } // end method earnings
33 Call superclass’s earnings method
34 // return String representation of BasePlusCommissionEmployee object
35 public String toString()
36 {
Override toString method
37 return String.format( "%s %s; %s: $%,.2f",
38 "base-salaried", super.toString(),
39 "base salary", getBaseSalary() );
40 } // end method toString
41 } // end class BasePlusCommissionEmployee
Call superclass’s toString method

31
31
1 // PayrollSystemTest.java
2 // Employee hierarchy test program.
3
4 public class PayrollSystemTest
5 {
6 public static void main( String args[] )
7 {
8 // create subclass objects
9 SalariedEmployee salariedEmployee =
10 new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 );
11 HourlyEmployee hourlyEmployee =
12 new HourlyEmployee( "Karen", "Price", "222-22-2222", 16.75, 40 );
13 CommissionEmployee commissionEmployee =
14 new CommissionEmployee(
15 "Sue", "Jones", "333-33-3333", 10000, .06 );
16 BasePlusCommissionEmployee basePlusCommissionEmployee =
17 new BasePlusCommissionEmployee(
18 "Bob", "Lewis", "444-44-4444", 5000, .04, 300 );
19
20 System.out.println( "Employees processed individually:\n" );
21

32
32
22 System.out.printf( "%s\n%s: $%,.2f\n\n",
23 salariedEmployee, "earned", salariedEmployee.earnings() );
24 System.out.printf( "%s\n%s: $%,.2f\n\n",
25 hourlyEmployee, "earned", hourlyEmployee.earnings() );
26 System.out.printf( "%s\n%s: $%,.2f\n\n",
27 commissionEmployee, "earned", commissionEmployee.earnings() );
28 System.out.printf( "%s\n%s: $%,.2f\n\n",
29 basePlusCommissionEmployee,
30 "earned", basePlusCommissionEmployee.earnings() );
31
32 // create four-element Employee array
33 Employee employees[] = new Employee[ 4 ];
34
35 // initialize array with Employees
36 employees[ 0 ] = salariedEmployee; Assigning subclass objects
37 employees[ 1 ] = hourlyEmployee; to supercalss variables
38 employees[ 2 ] = commissionEmployee;
39 employees[ 3 ] = basePlusCommissionEmployee;
40
41 System.out.println( "Employees processed polymorphically:\n" );
42
43 // generically process each element in array employees
44 for ( Employee currentEmployee : employees )
45 {
46 System.out.println( currentEmployee ); // invokes toString

33
47
Implicitly and polymorphically call toString

33
48 // determine whether element is a BasePlusCommissionEmployee
49 if ( currentEmployee instanceof BasePlusCommissionEmployee )
50 {
51 // downcast Employee reference to
If the currentEmployee variable points to a
52 // BasePlusCommissionEmployee reference BasePlusCommissionEmployee object
53 BasePlusCommissionEmployee employee =
54 ( BasePlusCommissionEmployee ) currentEmployee;
55
Downcast currentEmployee to a
56 double oldBaseSalary = employee.getBaseSalary();
57 employee.setBaseSalary( 1.10 * oldBaseSalary );
BasePlusCommissionEmploy
58 System.out.printf( ee reference
59 "new base salary with 10%% increase is: $%,.2f\n",
60 employee.getBaseSalary() );
61 } // end if Give BasePlusCommissionEmployees
62
63 System.out.printf(
a 10% base salary bonus
64 "earned $%,.2f\n\n", currentEmployee.earnings() );
65 } // end for
66 Polymorphically call
67 // get type name of each object in employees array
68 for ( int j = 0; j < employees.length; j++ )
earnings method
69 System.out.printf( "Employee %d is a %s\n", j,
70 employees[ j ].getClass().getName() );
71 } // end main
72 } // end class PayrollSystemTest

Call getClass and getName methods to display


each Employee subclass object’s class name
34
34
Employees processed individually:
salaried employee: John Smith
social security number: 111-11-1111
weekly salary: $800.00
earned: $800.00
hourly employee: Karen Price
social security number: 222-22-2222
hourly wage: $16.75; hours worked: 40.00
earned: $670.00
commission employee: Sue Jones
social security number: 333-33-3333
gross sales: $10,000.00; commission rate: 0.06
earned: $600.00
base-salaried commission employee: Bob Lewis
social security number: 444-44-4444
gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00
earned: $500.00

35
35
Employees processed polymorphically:
salaried employee: John Smith
social security number: 111-11-1111
weekly salary: $800.00
Same results as when the employees
earned $800.00 were processed individually
hourly employee: Karen Price
social security number: 222-22-2222
hourly wage: $16.75; hours worked: 40.00
earned $670.00
commission employee: Sue Jones
social security number: 333-33-3333
gross sales: $10,000.00; commission rate: 0.06
earned $600.00
base-salaried commission employee: Bob Lewis
social security number: 444-44-4444
gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00
new base salary with 10% increase is: $330.00
earned $530.00
Employee
Employee
0
1
is
is
a
a
SalariedEmployee
HourlyEmployee
Base salary is increased by 10%
Employee 2 is a CommissionEmployee
Employee 3 is a BasePlusCommissionEmployee

Each employee’s type is displayed


36
36
§ class – a description of a set of objects

§ object – a member of a class


§ instance – same as “object”

§ field – data belong to an object or a class


§ variable – a name used to refer to a data object
§ instance variable – a variable belonging to an object
§ class variable, static variable – a variable belonging to the class as a whole
§ method variable – a temporary variable used in a method

37
§ method – a block of code that can be used by other parts of the program
§ instance method – a method belonging to an object
§ class method, static method – a method belonging to the class as a whole

§ constructor – a block of code used to create an object

§ parameter – a piece of information given to a method or to a constructor


§ actual parameter – the value that is passed to the method or constructor
§ formal parameter – the name used by the method or constructor to refer to that value

§ return value – the value (if any) returned by a method

38
§ hierarchy – a treelike arrangement of classes

§ root – the topmost thing in a tree


§ Object – the root of the class hierarchy

§ subclass – a class that is beneath another in the class hierarchy


§ superclass – a class that is above another in the class hierarchy

§ inherit – to have the same data and methods as a superclass

39
Review class notes. Additional reading: Start a discussion on Google
Examples of UML diagrams Groups to clarify your doubts.

40

You might also like