[go: up one dir, main page]

0% found this document useful (0 votes)
8 views24 pages

06 - Abstract (Compatibility Mode)

This document discusses abstract classes in object-oriented programming. It explains that abstract classes are classes that cannot be instantiated and are meant to be subclassed. Abstract classes may contain abstract methods that have no body and must be implemented by subclasses. The document provides examples of abstract classes like Animal and Shape that define common behaviors but are not objects themselves. Subclasses like Dog, Cat, Circle then implement the specific behaviors.

Uploaded by

hanguyenb1a4
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)
8 views24 pages

06 - Abstract (Compatibility Mode)

This document discusses abstract classes in object-oriented programming. It explains that abstract classes are classes that cannot be instantiated and are meant to be subclassed. Abstract classes may contain abstract methods that have no body and must be implemented by subclasses. The document provides examples of abstract classes like Animal and Shape that define common behaviors but are not objects themselves. Subclasses like Dog, Cat, Circle then implement the specific behaviors.

Uploaded by

hanguyenb1a4
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/ 24

Abstract classes

Object-Oriented Programming
Outline

Abstract classes
Abstract methods
Design pattern: Template method
Dynamic & static binding
Upcasting & Downcasting

Readings:
HFJ: Ch. 8.
GT: Ch. 8.

Đại học Công nghệ - ĐHQG HN Abstract classes 2


Our previous design
Dog d = new Dog();
Cat c = new Cat();

Fine. But…

Animal anim = new Animal();

What does an Animal look like?

Đại học Công nghệ - ĐHQG HN Abstract classes 3


What does an Animal look like?

What does a new Animal() object look like?


What are the values of its instance variables?
What should makeNoise(), eat(), and roam() do?

Do we ever need an Animal object?

Đại học Công nghệ - ĐHQG HN Abstract classes 4


What does a Shape look like?

What does a generic Shape object look like?


How to draw() it?
Shape
- x, y

Do we ever need a Shape object? + draw()


+ erase()

Point Circle Rectangle


- radius - width
+ draw() + draw() - height
+ erase() + erase() + draw()
+ erase()

Đại học Công nghệ - ĐHQG HN Abstract classes 5


Abstract classes

Some classes just should not be instantiated!


We want Circle and Triangle objects, but no Shape objects.
We want Dogs and Cats, but no Animal objects…
Make those generic classes abstract classes
abstract class Animal { ... }

The compiler will guarantee that no instances of abstract


classes are created.
But object references of abstract class types are allowed.

Animal a = new Animal(); // Error!!!


Animal anim = new Dog(); // no error.

Đại học Công nghệ - ĐHQG HN Abstract classes 6


abstract public class Animal {
public void eat() {}
... This is OK.
} You can always assign a subclass
object to a super class reference,
-----------------------------------------------
even if the superclass is abstract.
public class MakeAnimal {
public void go() {
Animal a;
class Animal is marked abstract,
a = new Hippo();
so the compiler will NOT let you
a = new Animal();
do create an instance of Animal.
a.eat();
}
} % javac MakeAnimal.java

MakeAnimal.java:5: Animal is abstract;


cannot be instantiated
a = new Animal();
^
1 error
Đại học Công nghệ - ĐHQG HN Abstract classes 7
Abstract vs. Concrete

A class that is not abstract


is called a concrete class

How do we know
when a class should
be abstract?

Đại học Công nghệ - ĐHQG HN Abstract classes 8


Abstract vs. Concrete

mobile phone
smart phone
iPhone
iPhone 4
iPhone 4S

Đại học Công nghệ - ĐHQG HN Abstract classes 9


Abstract methods

How do we implement? public void makeNoise() {


Animal.makeNoise(), eat()… System.out.print("Hmm");
}
We can't think of
a generic implementation that is useful

So, we mark those methods abstract.


Abstract methods has no body.

abstract public class Animal { No method body!


End it with a semicolon.
public abstract void makeNoise();
...

Đại học Công nghệ - ĐHQG HN Abstract classes 10


Abstract methods

If you declared a method abstract,


you must mark the class abstract, as well. You can't
have a concrete class with an abstract method.

An abstract class means that it must be extended.


An abstract method means that it must be overriden.

A concrete subclass must have all the inherited


abstract methods implemented.

Đại học Công nghệ - ĐHQG HN Abstract classes 11


abstract public class Shape {
protected int x, y;
Shape(int _x, int _y) {
x = _x;
y = _y;
}
abstract public void draw();
abstract public void erase();
public void moveTo(int _x, int _y) {
erase();
x = _x; public class Circle extends Shape {
y = _y; private int radius;
draw(); public Circle(int _x, int _y, int _r) {
} super(_x, _y);
} radius = _r;
}
public void draw() {
System.out.println("Draw circle at "+x+","+y);
}
public void erase() {
System.out.println("Erase circle at "+x+","+y);
}
}
Đại học Công nghệ - ĐHQG HN Abstract classes 12
Design pattern: Template method

abstract class Shape {


protected int x, y;

public void moveTo(int x1, int y1) {


erase();
x = x1;
y = y1;
draw();
}
abstract public void erase();
abstract public void draw();
}
Đại học Công nghệ - ĐHQG HN Abstract classes 13
Account example
You need to store information for bank accounts: current balance, and the total
number of transactions for each account.
The goal for the problem is to avoid duplicating code between the three types of
account.
An account needs to respond to the following messages:
constructor(initialBalance)
deposit(amount)
withdraw(amount)
endMonth(): Apply the end-of-month charge, print out a summary, zero the
transaction count.
The end-of-month charge is calculated depending on types of Accounts
Normal : Fixed $5.0 fee at the end of the month
Nickle ‘n Dime: $1.00 fee for each withdrawal charged at the end of the
month
Gambler:
With probability 0.49 there is no fee and no deduction to the balance
With probability 0.51 the fee is twice the amount withdrawn

Đại học Công nghệ - ĐHQG HN Abstract classes 14


Class design diagram
Account
*balance
*transactions
-deposit
-withdraw
-endMonth
-endMonthCharge (abstract)

Fee NickleNDime Gambler


-endMonthCharge *withdrawCount -withdraw
-withdraw -endMonthCharge
-endMonthCharge

Đại học Công nghệ - ĐHQG HN Abstract classes 15


public class AnimalList {
private Animal[] animals = new Animal[5];
private int nextIndex = 0;

public void add(Animal a) {


if (nextIndex < animals.length) {
animals[nextIndex] = a;
System.out.print("Animal added at " + nextIndex);
nextIndex++;
}
} public class AnimalTestDrive {
} public static void main(String [] args) {
AnimalList list = new AnimalList();
Dog d = new Dog();
Cat c = new Cat();
list.add(d);
list.add(c);
}
}
Đại học Công nghệ - ĐHQG HN Abstract classes 16
public class AnimalList {
private Animal[] animals = new Animal[5]; AnimalList
private int nextIndex = 0;
Animal[] animals
public Animal get(int index) { int nextIndex
return animals[index];
} add(Animal a)
get(int index)
public void add(Animal a) {
if public
(nextIndex
class< DogTestDrive
animals.length)
{ {
animals[nextIndex] = a;
public static void main(String [] args) {
System.out.print("Animal
AnimalList list = newadded at " + nextIndex);
AnimalList();
nextIndex++;
Dog d = new Dog();
} list.add(d);
} d = list.get(0); // Error!
} d.chaseCats();
% javac DogTestDrive.java
}
DogTestDrive.java:6: incompatible types
}
found : Animal
The compiler doesn't know that required: Dog
list.get() refers to a Dog object! d = list.get(0);
^
Đại học Công nghệ - ĐHQG HN Abstract classes 17
public class AnimalList {
private Animal[] animals = new Animal[5];
private int nextIndex = 0;

public Animal get(int index) {


return animals[index];
}

public void add(Animal a) {


if public
(nextIndex
class< DogTestDrive
animals.length)
{ {
animals[nextIndex] = a;
public static void main(String [] args) {
System.out.print("Animal
AnimalList list = newadded at " + nextIndex);
AnimalList();
nextIndex++;
Dog d = new Dog();
} list.add(d);
}
} Animal a = list.get(0); // We know the object is a Dog!
a.chaseCats(); // Error! Animal doesn't have chaseCats()!
}
}
The compiler doesn't know that
a refers to a Dog object!

Đại học Công nghệ - ĐHQG HN Abstract classes 18


Subclass object & the inherited part

The Object remote control


has fewer buttons!
Đại học Công nghệ - ĐHQG HN Abstract classes 19
The rules

Which method version get invoked depends on the object


type.
Whether a method call is allowed depends on the reference
type – what buttons the remote control has.
Object o = new Cow();
o.toString();
o.moo();

Cow's toString() is invoked because o is now refering to an


Cow object.
o.toString() is allowed because Object has toString(). But
o.moo() is not allowed because Object does not has moo()

Đại học Công nghệ - ĐHQG HN Abstract classes 20


Dynamic & static binding

Method binding: connect a method call to a method


body
Static/early binding: performed by compiler/linker
before the program is run.
The only option of procedural languages.
Dynamic/late binding: performed during run-time
Java uses late binding, except for static, final, and
private methods.
private methods are implicitly final.

Đại học Công nghệ - ĐHQG HN Abstract classes 21


Casting Object o = new Cow();
o.toString();
o.moo(); // Error!

How to make the Cow


act like a Cow, again? Object o = new Cow();
o.toString();
Use an explicit cast: Cow c = (Cow) o;
c.moo(); // no error

( ): cast operator, casting to the type Cow

Explicit cast is not always possible:


Object o = new Cat();
Cow c = (Cow) o; // no compile-time error
c.moo(); // run-time error

Đại học Công nghệ - ĐHQG HN Abstract classes 22


Upcasting & down casting

Upcasting: Downcasting:
casting up the diagram. casting down the diagram.

Object
Object o = new Cow(); Object o;
...
Cow c = (Cow) o;

implicit casting
from Cow to Object Cow
explicit casting
from Object to Cow
+ moo()

Đại học Công nghệ - ĐHQG HN Abstract classes 23


Abstract super class

As a super class
A common superclass for several subclasses
Factor up common behavior
Define the methods all the subclasses respond to
As an abstract class
Force concrete subclasses to override methods that are
declared as abstract in the super class
Circle, Triangle must implement their own draw() and erase()
Forbid creation of instants of the abstract superclass
Shape objects are not allowed

Đại học Công nghệ - ĐHQG HN Abstract classes 24

You might also like