More on Objects & Classes

Download Report

Transcript More on Objects & Classes

More on Objects & Classes
Short Review
Examples of





Objects and classes, with fields/attributes and
methods/operations
Inheritance, multiple inheritance
Encapsulation
Polymorphism
Aggregation
Using a bit of Java code
Structure of OO-Programs
program
consists of
classes
consists of
members
are
fields/attributes
methods/operations
Examples of Classes
File
Files
file name
size in bytes
last update
print a number of copies
word count
rename
Java Pseudo-Code
class File {
private String name;
private int size;
private Date last_update;
File () {}
File (String n) {name = new String (n);};
void print (int c) { -- implementation code -- }
int word_count () { -- implementation code -- }
void rename (String new_name) { -- … -- }
}
Class instances
Creating a new file object; in Java:
File my_file = new File ();
File my_file = new File (“letter.doc”);
Note constructor overloading
Accessing methods & attributes
my_file.print;
my_file.rename(“letter2.doc”);
vs. my_file.name = “letter2.doc”; ???
Private vs. public fields & methods
Encapsulation
Including a number of items into a
single unit
A class encapsulated attributes and
methods
Thinking in terms of classes/objects and
their associated attributes & operations
Related notion: information hiding
private vs. public attributes/methods
 direct vs. indirect access to attributes

Example of Inheritance
Nature
Plants
Animals
Herbivores
Humans
Carnivores
Details of Classes
Nature
Humans
name
nationality
age
hair color
grow
speak
Herbivores
grass needed
walk
Inheritance in Java (1)
Class Nature {
private String name;
private int age;
void grow () {age ++}
…
}
Inheritance in Java (2)
Class Humans extends Nature {
private String nationality;
private String hair_color;
void speak () {… may refer e.g. to name …}
void walk () {… may use e.g. grow …}
…
}
Multiple Inheritance
Vehicle
Land Vehicle
Car
Water Vehicle
Amphibious Vehicle
Boat
Problems with multiple
inheritance
Possible clashes of methods
Example: suppose that both land and
water vehicles have a start_engine
method; for an amphibious vehicle
duck, we might want to say
duck.start_engine
But which method should be invoked?
Polymorphism
The same operation takes different
forms in different classes
Example: the operation grow is shared
by all objects of the nature class, but
may be different (in implementation) for
humans and animals
Aggregation
Document
Paragraph
Sentence
•A document consists of zero or more paragraphs
•A paragraph consists of zero or more sentences
Computer
+1
Monitor
Systembox
Keyboard
Mouse
Aggregation vs. Inheritance
Aggregation is NOT inheritance:
Inheritance: is-a, is-a-kind-of, subclass-of;
OR
 Aggregation: is-a-part-of; AND

Properties of aggregation: transitivity,
antisymmetry
Additional property of inheritance:
propagation of attributes and methods