0% found this document useful (0 votes)
1 views

lect04-week3

The document discusses object-oriented programming principles, focusing on relationships such as inheritance, encapsulation, abstraction, and polymorphism. It explains how to implement these relationships in Java, including examples of class hierarchies, method overloading, and overriding. Additionally, it covers the use of interfaces and abstract classes, emphasizing their roles in defining behaviors and relationships in object-oriented design.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

lect04-week3

The document discusses object-oriented programming principles, focusing on relationships such as inheritance, encapsulation, abstraction, and polymorphism. It explains how to implement these relationships in Java, including examples of class hierarchies, method overloading, and overriding. Additionally, it covers the use of interfaces and abstract classes, emphasizing their roles in defining behaviors and relationships in object-oriented design.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Programming2(CS272)

Lecture 4
Object-Oriented Relationships

1
Object- Oriented Programming (CS243/CS612) lec10
lect4 Dr Walid M. Aly
The four OOP Principles

Abstraction Encapsulation Association Polymorphism

Object-Oriented Relationships
Association UML symbol

Aggregation : has a
Composition: owns a
Inheritance : is a

Implementation : provides a
2
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Implementing Object-Oriented Relationships : is a
“ employee is a person ”

class Person class Employee extends Person


{ {

} }

“ car loan is a loan ”


class Loan class CarLoan extends Loan
{ {

} }

Inheritance
Is a relationship is implemented by making a class extends another class

3
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Inheritance: is a relationship
• When creating a class, rather than declaring completely
new members, the programmer can designate that the
new class inherit the members of an existing class.
• The existing class is called the superclass, and the new
class is the subclass.
• A subclass normally adds its own fields and methods.

class A{
int i; class Test{
int j; public static void main (String [] arg){
void m1(){} B b1=new B();
} b1.i=10;
b1.m1();
class B extends A{ }}
int k;
void m2(){}
4
Object- Oriented Programming (CS243/CS612) } lec10 Dr Walid M. Aly
Inheritance: is a relationship
• Each subclass can become the superclass for future
subclasses.
• Multiple inheritance is not allowed.
• In Java, the class hierarchy begins with class
java.lang.Object which every class in Java directly or
indirectly extends (or "inherits from").

5
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Inheritance examples.
Subclasses Superclass

GraduateStudent, UndergraduateStudent Student


Circle, Triangle, Rectangle Shape
Loan
CarLoan, HomeImprovementLoan, MortgageLoan

SalariedEmployee,CommisionEmployee Employee
CheckingAccount, SavingsAccount BankAccount

UML Employee Hierarchy Diagram


class Employee
{
}

class CommisionEmployee extends employee


{………………..
}
class SaliredEmployee extends employee
{……………..
}
6
UML defines
Object- Oriented inheritance
Programming lec10
as a generalization relation
(CS243/CS612) Dr Walid M. Aly
A Simple Inheritance case study
public class Person{ public class Student extends Person{
private String name; private int registerationNumber;
public Person () public Student ()
{} {}
public void setName (String name){ public void setRegisterationNumber (int registerationNumber){
this.name=name; this.registerationNumber=registerationNumber;
} }
public String getName(){ public int getRegisterationNumber(){
return name; return registerationNumber;
} }
}
}

public class Test{


public static void main (String [] arg)
{
Student student1=new Student();
student1.setName ("Ahmed Hussien");
student1.setRegisterationNumber(4564);
}
} 7
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Calling a subclass constructor invokes super class constructor

Creating an instance of sub class means automatically creating an instance of the super class
by invoking the default no argument constructor.
Java adds automatically super() to the first line in the constructor of sub class to invoke the
default no argument constructor of the super class.

8
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
inheritance hierarchy

Class A

More
More

More
More
Specific
general

Specific
class B

general
class c

In the inheritance hierarchy, classes become more specific and concrete with each new subclass.
If you move from a subclass back up to a superclass, the classes become more general and less
specific.
Class design should ensure that a superclass contains common features of its subclasses.
More generalization means reaching the abstraction level

9
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Modifier : abstract
A method or a class can be declared as abstract.
Access modifiers and abstract keyword can appear in any order.

abstract method
An abstract method is just a method signature without any
implementation.
abstract methods cannot have a body.
Abstract methods can not be static
A constructor can never be declared as abstract.
If a class has any abstract methods it must be declared as abstract.

public abstract class M


{
abstract public void m1();
void m2()
{
}
}
10
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
abstract class
No objects can be created from an abstract class.
It is possible to execute the static methods of abstract classes
An abstract class forces its user to create a subclass to execute
instance methods
Subclasses of this abstract class will have to implement the abstract
methods of abstract class or declared as abstract themselves.
A class can be declared abstract even if no abstract methods is
included.

abstract class Player class FootbalPlayer extends Player


{ {
int age; public void play ()
public int getAge() {
{return age;} ……………..
public abstract void play (); }
}
11
}Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Example : extending abstract class
public class Circle extends Shape {
private double radius;
public Circle(double radius){
this.radius=radius;
}
public class Rectangle extends Shape{ public double calculateArea()
private double height, width; {
public Rectangle( double height,double width) return 3.14*radius*radius;
{ }
this.height=height; }
this.width=width;
}
public double calculateArea()
{
return height*width;
}

Abstract elements are italic in UML Diagrams

12
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Implementing Object-Oriented Relationships : provides a
▪An interface is a classlike that contains only constants and abstract
methods and no constructors.
▪A class implements an interface by implementing all methods in the
interface.
▪An interface represents the relation “provides a”(promises).
▪If a class is declared to implement an interface and does not implement
all the methods in the interface , it must be declared abstract otherwise
a compile error
An interface can extend one or more interfaces..
A class can implements more than one interface.

Company provides Payable

public interface Payable class Company implements Payable{


public double getPaymentAmount()
{
{
double getPaymentAmount(); ////
} }
Object- Oriented Programming (CS243/CS612)
} lec10 Dr Walid M. Aly
Interface names may be adjectives or nouns.
Variables in interfaces are implicitly Public, static and final
and should be initialized with a value.
Methods in interface are implicitly public (even if left
without a modifier) and abstract (even if abstract
modifier is not declared), they should be implemented
only by public methods.
Methods declared in an interface can be declared as
abstract (although unneeded).
Interface says what a class can do without saying how.

https://www.studytonight.com/java/java-interface.php
14
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Interface
• interface can have default and static
methods and can have private methods as
well.

https://www.studytonight.com/java/java-interface.php
Casestudy :Payable interface
public interface Payable public class Invoice implements Payable
{ {
double getPaymentAmount(); private int quantity;
} private double pricePerItem;
Invoice(int quantity,double pricePerItem )
public class Employee implements Payable {
{ this.quantity=quantity;
private int days; this.pricePerItem=pricePerItem;
private double dayWage; }
Employee(int days,double dayWage ) public double getPaymentAmount()
{ {
this.days=days; return quantity*pricePerItem;
this.dayWage=dayWage; }
} }
public double getPaymentAmount()
{
return dayWage*days;
}
}

16
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
17
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
The four OOP Principles

Abstraction Encapsulation Association Polymorphism

Object-Oriented Relationships
Association UML symbol

Aggregation : has a
Composition: owns a
Inheritance : is a

Implementation : provides a
18
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Polymorphism
• polymorphism: The ability for the same code to behave differently depending on the type of
argument used.

class Person
Open(Window w) Method Overloading
Open (Present p)
Open(BankAccount ba)

• polymorphism: The ability for the same code to be used with several different types of
objects and behave differently depending on the type of object used.

Method Overriding
+
Dynamic method dispatch
Dynamic method dispatch is a
mechanism by which a call to
an overridden method is
resolved at runtime.

https://www.studytonight.com/java/d
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Alyynamic-method-dispatch.php
Polymorphism with Method Overloading

Method overloading : define two or more methods within the same class that share the
same name, as long as their parameter declarations are different.

Without using Overloading With Overloading

class Math class Math


{ {
int absoluteInt(int x) int absolute(int x)
{…..} {…..}
double absoluteDouble(double x) double absolute(double x)
{…..} {…..}
float absoluteFloat(float x) float absolute(float x)
{…..} {…..}
} }

20
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
class A
{
void m1(int x )
{ …}
Method calling
void m1(int x, int y)
{…} m1(3);
void m1(double x) m1(3,4);
{…} m1(0.7);
void m1() m1();
{…} Int x=m1(“Hello”);
int m1(String S)
{…}
}

When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to
actually call.
overloaded methods must differ in the type and/or number of their parameters.
The return type alone is insufficient to distinguish two versions of a method.

java.util.Random
int nextInt()
int nextInt(int n) 21
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Two Basic Rules for Overloading
1-Automatic type conversions
If match of a certain argument is not exactly met, automatic type conversions can play a role in overload
resolution as long as the data type argument of the method calling is smaller than the data type of the
argument in method signature
class A{
void test(){…}
void test(int a, int b) {..}
void test(double a) {..} test(2);
}

2-ambiguous invocation.
If a calling to a method is ambiguous will result in a compile error
class A
{….
double max(int num1, double num2) ?
{…} max(1, 2);
?
double max(double num1, int num2)
{….}
22
}Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Method Overriding
when a method in a subclass has the same name and type signature as a method in its
superclass, then the method in the subclass overrides the method in the superclass.
When an overridden method is called by an object from a subclass, it refers to the version of
that method defined by the subclass.
By overriding, the subclass redefines the behavior of a method.

class Employee{ Overriding Rules


public double getSallary(){ 1. The two methods must have :same
return 1000;}} name-same arguments same return type.
2. The access modifier of an overriding
class Manager extends Employee{ must provide at least as much access as
public double getSallary(){ the overridden method,.
return 1500; 3. Static /non static methods can only be
}} overridden by static /non static methods,
public class Test{
public static void main(String [] arg){
Employee emp=new Employee();
Manager manager=new Manager();
double salary1=emp.getSallary();//1000
double salary2=manager.getSallary();//1500
}}
23
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Using super to overcome member hiding.
A manager takes 500 L.E. more than an employee
The keyword super can be used at the subclass to point to members of superclass

class Employee
{ class Manager extends Employee
private double salary=1000; {
public double getSalary() public double getSalary()
{ {
return salary; return super.getSalary()+500;
} }
} }

public class Test{


public static void main(String [] arg)
{
Employee emp=new Employee();
Manager manager=new Manager();
double salary1=emp.getSalary(); //1000
double salary2=manager.getSalary();//1500
}}

Usage : super.member
24
member
Object- Orientedcan be either
Programming lec10
a method or an instance variable
(CS243/CS612) Dr Walid M. Aly
Class Object
java.lang.Object

public class Object


Class Object is the root of the class hierarchy. Every class has Object as a superclass.
All objects, including arrays, implement the methods of this class.

Constructor Summary
Object()

Method Summary

protected Object clone() Creates and returns a copy of this object.

public boolean equals(Object obj) : Indicates whether some other object is "equal to" this one.

public String toString() Returns a string representation of the object.

25
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
object.toString()
Method toString returns the Hash code for the object, this method is called automatically by
System.out.println
A hash code is an integer value that is associated with each object in Java.

class A{
int i; class Test
int j; {
A(int i,int j) public static void main (String[] arg){
{ A a1=new A(3,4);
this.i=i; System.out.println(a1.toString());
this.j=j; }}
}
}

System.out.println(a1) System.out.println(a1.toString());

26
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Overriding object.toString()

class A
{ class Test
int i; {
int j; public static void main (String[] arg){
A(int i,int j) A a1=new A(3,4);
{ System.out.println(a1);
this.i=i; }}
this.j=j;
}
public String toString()
{ i=3 j=4
String s="i="+i+" j="+j;
return s;
}

27
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Case Study :Law Firm

• Consider the following employee regulations:


– Employees make a salary of L.E.40,000 per year, except legal secretaries who make
L.E5,000 extra per year (L.E.45,000 total), and marketers who make L.E. 10,000 extra
per year (L.E.50,000 total).
– Employees have 10 days of paid vacation leave per year, except lawyers who get an
extra 5 days.
• Each type of employee has some distinct behavior:
– Lawyers know how to sue.
– Marketers know how to advertise.
– Secretaries know how to take dictation.
–13:08Legal secretaries know how to prepare legal documents.
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly 28
class Employee{ class Marketer extends Employee
private double salary; {
private int vacationDays; public double getSalary()
public Employee(){ {
vacationDays=10; return super.getSalary()+10000;
sallary=40000; }
}
public void advertise(){}
public double getSalary(){
return salary;
}
}
public double getVacationDays(){
class Secretary extends Employee
return vacationDays;
{
}
public void takeDectattion(){}
}
}

class Lawyer extends Employee


{ class LegalSecretary extends Secretary {
public double getVacationDays() public double getSalary()
{ {
return super.getVacationDays()+5; return super.getSalary()+5000;
} }
public void sue(){} public void prepareLegalDocuments(){}
} 13:08 } 29
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Modification1: Raise
• everyone is given a L.E.10,000 raise.
– The base employee salary is now L.E.50,000.
– Legal secretaries now make L.E.55,000.
– Marketers now make L.E.60,000.

public class Employee {


private int vacationDays;
private int sallary;

public Employee(){
vacationDays=10;
sallary=50000;
}
//…………………………………………………………………
}

30
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Modification2: vacation days related to years of employment
• give employees –except Secretaries -more vacation days the longer they've
been with the company. For each year worked, 2 additional vacation days.

class Employee { class Lawyer extends Employee


private int vacationDays; {
private int sallary; public Lawyer(int years) {
private int years; super(years);
public Employee(int years){ }
this.years=years; ...
vacationDays=10; }
sallary=40000;
}
public int getYears() class Marketer extends
{return years; } Employee {
public void setYears(int years) public Marketer(int years)
{this.years=years;} {
super(years);
public int getVacationDays() { }
...
return vacationDays+ 2 * years;
} }
...
}
31
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
public class Secretary extends Employee {
An public Secretary() {
unsatisfactory super(0);
}
solution ...
}

public class Secretary extends Employee {


public Secretary(int years) {
super(years);
}
A satisfactory
solution public int getVacationDays() {
return vacationDays;
}
...
}
}

32
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
A more satisfactory solution

public class Employee {


...
public int getVacationDays() {
return vacationDays+ getSeniorityBonus();
}
public int getSeniorityBonus() {
return 2 * years;
}
...
}

public class Secretary extends Employee {


public Secretary(int years) {
super(years);
}
public int getSeniorityBonus() {
return 0;
}
...
}
}
33
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
polymorphic references
Rule 1
A reference variable of a type class T can legally refer to an object of T or any subclass of T.

class T class K extends T


{ { T t1=new K();
} }

Rule 2
A reference variable of a type interfaces T can legally refer to an object of classes implementing
interface T

interface T class K implements T


{ { T t1=new K();

} } 34
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Dynamic method dispatch
Dynamic Method Dispatch is a process in which a call to an overridden
method is resolved at runtime rather than compile-time.
Java determines which version of that method to execute based upon
the real type of the object being referred to at the time the call occurs.

class A { class Test {


void callme() { Pub lic static void main(String args[]) {
System.out.println("Inside A's callme method"); A a = new A(); // object of type A
} A b = new B(); // object of type B
} a.callme(); // calls A's version of callme
b.callme(); // calls B's version of callme
}
class B extends A {
}
void callme() {
System.out.println("Inside B's callme method");
}
}

35
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Dynamic method dispatch : Example from the case study

Employee person = new Lawyer();


int days=person.getVacationDays();// days =15

Object type : class Lawyer

Reference type : class Employee

– The reference person of type Employee pointing to an object of type Lawyer


will act as a lawyer , and call getVacationDays() of class Lawyer not Employee
– You can call any methods from Employee on the variable person, but not any
methods specific to Lawyer (such as sue).
– Person.sue() // compile error

36
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Benefits of polymorphism(1)

A method declaring in its argument list a super class data type can receive an object of any of
its subclasses.
class D{
class A polymorphism public void m(A a){
{
//////
int i=9;
a.m1();
void m1(){} ? /////
}
}
class B extends A }
{ ?
Class Test{
int j=10; public static void main (String [] arg){
void m1(){} D d=new D();
void m2(){}
} ? A a1=new A();
B b1=new B();
class C extends A C c1=new C();
{ d.m(a1);
void m1(){} d.m(b1);
void m2(){} d.m(c1);
} }
}
37
N.B. : Method
Object- Oriented m can
Programming lec10 of class A
only access the member variables
(CS243/CS612) Dr Walid M. Aly
Benefits of polymorphism(1)

A method declaring in its argument list a super class data type can receive an object of any of
its subclasses.

public class EmployeeMain {


public static void printInfo(Employee empl) {
System.out.println("salary = " + empl.getSalary());
System.out.println("days = " + empl.getVacationDays()); polymorphism
System.out.println();
}
public static void main(String[] args) {
Lawyer lisa = new Lawyer();
Secretary steve = new Secretary();
printInfo(lisa);
printInfo(steve);
}
}

With polymorphism, it is possible to design and


implement systems that are more easily extensible.
Programs can be written to process even objects of
types that do not exist when the program is under
development.
38
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Benefits of Abstract methods and Polymorphism

abstract class A{
public abstract void m(); public class Test{
} public static void m2(A a1){
a1.m();
class B extends A { }
public void m(){
System.out.println("Hello from class B");}
} public static void main (String [] arg){
C c1=new C();
m2(c1);
class C extends A { }
public void m(){ }
System.out.println("Hello from class C");
}
}

39
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Benefits of polymorphism(2)
You can declare arrays of superclass types, and store objects of any subtype as elements.

Example
public class Test {
public static void main(String[] args) {
Employee[] employees = {new Lawyer(), new Secretary(),
new Marketer(), new LegalSecretary()};
for (int i = 0; i < employees.length; i++) {
System.out.println("salary = " +employees[i].getSalary());
System.out.println("vacation days="+employees[i].getVacationDays());
System.out.println();
}
}
}

40
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Benefits of polymorphism(3)
A method declaring in its argument list an interface data type can receive an object of any
class implementing the interface.
class D {
interface Y
polymorphism public void m2(Y y )
{
{
int x=9;
…………
void m1();
}
? y.m1();
}
? }
class A implements Y{
public void m1(){} Class Test{
public void m2(){} public static void main (String [] arg){
} D d=new D();
? A a1=new A();
class B implements Y{ B b1=new B();
public void m1(){} Y c1=new C();
} d.m2(a1);
class C implements Y{ d.m2(b1);
public void m1(){} d.m2(c1);
} }}

N.B. : reference y can only access the member of interface Y


41
Dynamic
Object- OrientedMethod
ProgrammingDispatch
(CS243/CS612) is applied lec10 Dr Walid M. Aly
Benefits of polymorphism(4)
We can create an array of an interface type, and store any object implementing that
interface as an element.

Circle circ = new Circle(12.0);


Rectangle rect = new Rectangle(4, 7);
Triangle tri = new Triangle(5, 12, 13);
Shape[] shapes = {circ, tri, rect};

Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly


Questions
• Java main() method is always static, so that
compiler can call it without the creation of an
object or before the creation of an object of the
class.
• Java main() method is always public as the Java
program is invoked from outside the Class
• Why void: if not void, so there has to be some
returned value of main but JVM will process the
main only. So there is no place or something
which store the status of main.
• Parameters of main: It is its signature

You might also like