lect04-week3
lect04-week3
Lecture 4
Object-Oriented Relationships
1
Object- Oriented Programming (CS243/CS612) lec10
lect4 Dr Walid M. Aly
The four OOP Principles
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 ”
} }
} }
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
SalariedEmployee,CommisionEmployee Employee
CheckingAccount, SavingsAccount BankAccount
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.
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.
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
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.
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
{ class Manager extends Employee
private double salary=1000; {
public double getSalary() public double getSalary()
{ {
return salary; return super.getSalary()+500;
} }
} }
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
Constructor Summary
Object()
Method Summary
public boolean equals(Object obj) : Indicates whether some other object is "equal to" this one.
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
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.
32
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
A more satisfactory solution
Rule 2
A reference variable of a type interfaces T can legally refer to an object of classes implementing
interface T
} } 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.
35
Object- Oriented Programming (CS243/CS612) lec10 Dr Walid M. Aly
Dynamic method dispatch : Example from the case study
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.
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);
} }}