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

Lab08 Abstract Classes & Polymorphism

This document discusses object-oriented programming concepts like polymorphism, abstract classes, and binding. It defines polymorphism as the ability for one method name to have multiple meanings through late binding. Late binding associates a method definition with a method invocation at runtime rather than compile time. The document also discusses abstract classes, which can contain abstract methods that are placeholders without a method body. Derived concrete classes must implement abstract methods.

Uploaded by

Jinwoo Song
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Lab08 Abstract Classes & Polymorphism

This document discusses object-oriented programming concepts like polymorphism, abstract classes, and binding. It defines polymorphism as the ability for one method name to have multiple meanings through late binding. Late binding associates a method definition with a method invocation at runtime rather than compile time. The document also discusses abstract classes, which can contain abstract methods that are placeholders without a method body. Derived concrete classes must implement abstract methods.

Uploaded by

Jinwoo Song
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Object – Oriented Programming

Lab 8
Contents
• Polymorphism
– Binding
– Casting

• Abstract Classes

2
Introduction to Polymorphism
• There are three main programming mechanisms that constitute
Object Oriented Programming (OOP)
– Encapsulation: { combining data and actions into a single unit (Class) }
– Inheritance: { deriving information and functionality from base or super class}
– Polymorphism
• What is Polymorphism?

• Comes from 2 Greek words


– poly (many)
– morph (forms, shapes)

3
Introduction to Polymorphism (Contd)

• Polymorphism is the ability to associate many meanings to one


method name by means of a late binding mechanism
– It does this through a special mechanism known as late binding or
dynamic binding

4
Introduction to Polymorphism (Contd)

• Inheritance allows a base class to be defined, and other classes


derived from it
– Code for the base class can then be used for its own objects, as well as
objects of any derived classes

Code use
super
this.getX();
super.toString();
this

5
Introduction to Polymorphism (Contd)

• Polymorphism allows changes to be made to method definitions


in the derived classes, and have those changes apply to the
software written for the base class

super
Some auto

this

6
Introduction to Polymorphism (Contd)

• Overloading can be an example of Polymorphism as well

7
Introduction to Polymorphism (Contd)

8
Introduction to Polymorphism (Contd)

9
Introduction to Polymorphism (Contd)

10
Introduction to Polymorphism (Contd)

11
Introduction to Polymorphism (Contd)

12
Binding
• The process of associating a method definition with a method
invocation is called binding

13
Binding
• If the method definition is associated with its invocation when the
code is compiled, that is called early binding or static binding

• If the method definition is associated with its invocation when the


method is invoked (at run-time), that is called late binding or
dynamic binding

• Java uses late binding for all methods


– Except for a few cases discussed later

14
No Late Binding for Static Methods
• When the decision of which definition of a method to use is
made at compile time, that is called static binding
– This decision is made based on the type of the variable naming the
object
• Java uses static, not late binding with private, final, and static
methods
– In the case of private and final methods, late binding would serve no
purpose
– However, in the case of a static method invoked using a calling object, it
does make a difference

15
Late Binding

16
Late Binding

17
Self-Test (1)
• 프로젝트 명: Project08_1
– git commit –m “Project08_1”
• Sale 클래스에 다음 메소드를 작성할 것
– 두 객체의 name과 bill()이 동일할 경우 true를 반환하는 equalDeals(Sale
otherSale) 메소드를 작성할 것
– 호출한 객체의 bill()이 인자의 bill()보다 작을 경우 true, 큰 경우 false를 반
환하는 lessThan(Sale otherSale) 메소드를 작성할 것

• DiscountSale 클래스에 다음 메소드를 작성할 것


– Sale 클래스의 bill() 메소드를 DiscountSale 클래스의 할인율(discount)이 적
용된 값을 반환하는 bill() 메소드로 override 할 것
• discount 값은 %(percentage)이다.
– 두 객체의 name, bill, discount가 동일할 경우 true를 반환하는
equals(Object obj)를 작성할 것

18
Self-Test (1) (Contd)
• Mart 클래스의 main 메소드를 수행했을 때 다음과 같이 출력되어야 함

19
The final Modifier
• A method marked final indicates that it cannot be overridden
with a new definition in a derived class
– If final, the compiler can use early binding with the method

public final void someMethod() { … }

• A class marked final indicates that it cannot be used as a base


class from which to derive any other classes

20
Upcasting and Downcasting
• Upcasting is when an object of a derived class is assigned to a
variable of a base class (or any ancestor class)

• Downcasting is when a type case is performed from a base class


to a derived class (or from any ancestor class to any descendent
class)
– Downcasting has to be done very carefully
– In many cases it doesn’t make sense, or is illegal

21
Upcasting and Downcasting (Contd)
• Downcasting makes sense only if the object to be cast is an
instanceOf the class type

if(myObject instanceOf ClassType) {


ClassType classObject = (ClassType) myObject;
// now you can use classObject form here
}

22
Upcasting and Downcasting (Contd)

Cat c = new Cat();


Mammal m = c; // upcasting

Cat c1 = new Cat();


Animal a = c1; // automatic upcasting to Animal
Cat c2 = (Cat) a; // manual downcasting back to a Cat

23
A First Look at the clone Method
• Every object inherits a method name clone from the class Object
– The method clone has no parameters
– It is supposed to return a deep copy of the calling object

• However, the inherited version of the method was not designed


to be used as is
– Instead, each class is expected to override it with a more appropriate
version

24
A First Look at the clone Method
• The heading for the clone method defined in the Object class is
as follows:
protected Object clone()

• The heading for a clone method that overrides the clone method
in the Object class can differ somewhat from the heading above
– A change to a more permissive access, such as from protected to public,
is always allowed when overriding a method definition
– Changing the return type from Object to the type of the class being
cloned is allowed because every class is a descendent class of the class
Object

25
Simple clone Method
• We can define a simple clone method by using the copy
constructor

public ClassType clone() {


return new ClassType(this)
}

• This is a very simple clone method, however more checks should


be done before cloning
– We do not cover this until Chapter 13

26
Example

27
Abstract Classes
• Some classes may be defined with incomplete methods
definitions (abstract methods).

• Such classes are said to be abstract

• Such classes cannot be instantiated but must be extended by a


concrete class

• The concrete class must implement all abstract methods


– If all abstract methods cannot be implemented then the class must also
be marked as abstract

28
Abstract Classes (Contd)
• Definitions
– An abstract class is a class that contains one or more abstract methods
and therefore cannot be instantiated

– Abstract methods are methods that without complete definitions. instead,


they are simple placeholders

– A concrete class is a class that contains no abstract methods and


therefore can be instantiated

29
Abstract Method
• It cannot be private

• It has no method body, and ends with a semicolon in place of its


body

public abstract double getPay();


public abstract void doIt(int count);

30
Tip: An Abstract Class Is a Type
• Although an object of an abstract class cannot be created, it is
perfectly fine to have a parameter of an abstract class type
– This makes it possible to plug in an object of any its descendent classes

• It even make sense to have a variable of an abstract class type,


although it can only name objects of its concrete descendent
classes

31
Defining Abstract Class
• Defining an abstract class is simple

public abstract class Myclass {


// class constructors Abstract class header
// accessors and mutators Common fields and methods
// other methods Abstract Methods

public abstract returnType myMethod();


}

• When defining an abstract method only specify the header

public abstract returnType myMethod();

32
Defining Abstract Class

33
When to use
• Consider using abstract classes if any of these statements apply
to your situation:
– You want to share code among several closely related classes
– You expect that classes that extend your abstract class have many
common methods or fields, or require access modifiers other than
public (such as protected and private).
– You want to declare non-static or non-final fields. This enables you to
define methods that can access and modify the state of the object to
which they belong

34
Self-Test (2)
• 프로젝트 명: Project08_2
– git commit –m “Project08_2”
– 당일 밤 12시까지 제출
• Sale 클래스에 다음 메소드를 작성할 것
– 배송 비용을 반환하는 deliverFee() 메소드를 작성
– deliverFee() 메소드는 할인율과 남은 유통기한에 따라 달라지므로 Sale 클
래스에서는 abstract 메소드로 선언
– 배송 비용이 같은 지 여부를 반환하는 equalDeliverFee() 메소드 작성
(deliverFee() abstract 메소드를 사용할 것)
• DiscountSale 클래스에 다음 메소드를 작성할 것
– 매장에서는 제품의 할인율이 낮을 경우 무료 배송을 해주는 서비스를 진행
하고 있다.
– 할인율에 따라 달라지는 deliverFee() 메소드를 정의할 것
• 할인율 >= 80%: 배송비용 3$
• 30% <= 할인율 < 80%: 배송비용 2$
• 할인율 < 30%: 배송비용 없음

35
Self-Test (2) (Contd)
• ExpiredSale 클래스에 다음 메소드를 작성할 것
– 매장에서는 제품의 유통기한이 얼마 남지 않았을 경우 무료 배송을 해주는
서비스를 진행하고 있다.
– 유통기한에 따라 달라지는 deliverFee() 메소드를 정의할 것
• 유통기한 >= 10: 배송비용 3$
• 3 <= 유통기한 < 10: 배송비용 2$
• 1 < 유통기한 < 3: 배송비용 없음
– 유통기한이 1일 이하일 경우 현장판매만 가능하므로 오류 처리

36
Self-Test (2) (Contd)
• Mart 클래스의 main 메소드를 수행했을 때 다음과 같이 출력되어야 함

37

You might also like