Title: Object Oriented Programming
1Object Oriented Programming
2Overview
- Inheritance
- Constructors and Finalizers
- Composition versus Inheritance
- Polymorphism
- final Methods and Classes
- Interfaces
- Inner Classes
- Wrapper Classes
3Inheritance and Polymorphism
- New classes created from existing ones
- Can write code in a general way to handle
existing and future objects - Reusability saves time and allows for reuse of
quality, tested code - Heart of object oriented programming systems
4Inheritance
- Parent class, superclass, base class -- inherited
from - Child class, subclass -- does the inheriting
- Examples -- students, automobiles, mammals, etc.
- Relationship is of the is-a-kind-of or is-a
type
5Inheritance
- The keyword extends is used in the derived class
- class child-class extends parent-class
- Already used extends when creating Applets
- Child class can use inherited variables and
methods as if they were locally declared
6Java Example
public class Animals public static void
main (String args) Horse mister_ed
new Horse(1500) mister_ed.feet()
mister_ed.defined() // method main // class
Animals
7Java Example (contd)
public class Four_Legged protected int legs
4 public void feet()
System.out.println ("Number of limbs "
legs) // method feet //class
Four_Legged public class Horse extends
Four_Legged private int weight public
Horse (int wt) weight wt //
constructor public void defined()
System.out.println ("Weight " weight)
System.out.println ("Pounds per limb "
(weight / legs)) // method defined //
class Horse
8Output of Animals
9Graphical Notation
Four_Legged
Parent class
Horse
subclass
10Visibility Modifiers
- private -- can only be seen within that class
- public -- can be seen by all classes
- protected -- can only be seen by subclasses
- Applied to both variables and methods
- Inherited methods and variables retain their
original visibility - Inheritance is only one way -- from parent to
child
11Constructors
- Constructors are never inherited by a subclass,
even though they are public - A subclass calls the constructor of a parent by
using the keyword super - The super reference can only be used in the child
- If included, must be the first line of the child
constructor
12School Example
public class School public static void main
(String args) Student sammy new
Student ("Sammy", 5) Grad_Student pete
new Grad_Student ("Pete", 3,
"Teaching Assistant", 8.75)
sammy.info() System.out.println()
pete.info() pete.support() //
method main // class School
13School Example (contd)
public class Student protected String
name protected int num_courses
public Student (String student_name, int
classes) name student_name
num_courses classes // constructor
public void info() System.out.println
("Student name " name)
System.out.println ("Number of courses "
num_courses) // method info // class
Student
14School Example (contd)
public class Grad_Student extends Student
private String source private double rate
public Grad_Student (String student_name,
int classes, String
support_source, double hourly_rate)
super (student_name, classes) source
support_source rate hourly_rate
// constructor
public void support ()
System.out.println ("Support Source "
source) System.out.println ("Hourly pay
rate " rate) // method support // class
Grad_Student
15School Example Output
16Overriding
- When a subclass has a method and signature the
same as the super class, this is overriding - Often done in class hierarchies
- Which method is used depends on the object
calling the method -- i.e., if a subclass object
then the subclass method and if the super class
object then the super class method - Invoking the parent method within the child uses
super.method
17Overriding (School2)
public class School2 public static void
main (String args) Student sammy
new Student ("Sammy", 5) Grad_Student2
pete new Grad_Student2 ("Pete", 3,
"Teaching Assistant",
8.75) sammy.info()
System.out.println() pete.info() //
just call the one info method // method main //
class School2
18Overriding (School2)
class Student protected String name
protected int num_courses public
Student (String student_name, int classes)
name student_name num_courses
classes // constructor public void
info() System.out.println ("Student
name " name) System.out.println
("Number of courses " num_courses) //
method info // class Student
19Overriding (School2)
public class Grad_Student2 extends Student
private String source private double rate
public Grad_Student2 (String student_name, int
classes, String support_source,
double hourly_rate) super
(student_name, classes) source
support_source rate hourly_rate
// constructor public void info ()
super.info() // calls the parent method
System.out.println ("Support Source "
source) System.out.println ("Hourly
pay rate " rate) // method support //
class Grad_Student2
20School2 Output
21Class Hierarchies
Student
Grad_Student
Undergrad
Day
Evening
Degree
Non-degree
22Class Hierarchies
- A child may be a parent to another child
- A parent may have more than one child and these
children are called siblings - However, only one parent is allowed for a child
(single inheritance) - Common features kept as high in the hierarchy as
possible - Inheritance goes all the way down
- Maintain is-a-kind-of relationship
23Class Hierarchies
- Hierarchies are often revised and modified during
development - There is no single best hierarchy for all
situations - Binary approaches ( this and not this)
- Is Like approach -- similarities
- etc.
24Object Class
- All classes derived ultimately from the Object
class - If a class definition does not use the extends
clause then it is derived from the Object class - Some Object class methods
- toString() - returns name of object
- equals (Object obj) - tests equality of objects
- hashCode() - returns unique number for object
25finalizers
- Remember that superclass constructors are called
before the subclass does its thing - Finalizer methods are the same way -- the
superclass finalizer method should be called
before the subclass does its thing
26Polymorphism
- Invocation of a method may invoke different
methods at different times (dynamic method
binding) - Names of objects are actually references to an
object - An object reference has a type (given when it is
declared) - A reference of one type can refer to an object of
another type if they are related by inheritance
27Polymorphism (contd)
- For Example
- The object reference jane is of type student
- When done, both references refer to the
Grad_Student object mike
Student jane new Student() Grad_Student mike
new Grad_Student() jane mike
28Polymorphism (contd)
- Further
- Will both execute the print_grades() method in
the Grad_Student object, even though the
reference jane remains a Student type of reference
jane.print_grades() mike.print_grades()
29Subclass relationship to Superclass
- An object reference (variable name) can be
declared as a superclass reference then
instantiated with a subclass object - The reverse is not allowed (an object reference
cannot be declared as a subclass and then
instantiated as a superclass object)
30Polymorphism
import java.io. public class Poly public
static void main (String args) throws
IOException BufferedReader stdin new
BufferedReader (new InputStreamReader
(System.in), 1) int choice Mammal
thing null
31Polymorphism
do System.out.println("Which type of
mammal do you want to be?\n")
System.out.println(" 1. Dog")
System.out.println(" 2. Lion")
System.out.println(" 3. Mouse")
System.out.println(" 4. Horse\n")
System.out.print("Enter your choice ")
choice Integer.parseInt(stdin.readLine())
32Polymorphism
switch (choice) case 1
thing new Dog() break
case 2 thing new Lion()
break case 3 thing
new Mouse() break
case 4 thing new Horse()
break default
System.out.println("\nThanks for playing...")
33Polymorphism
if ((choice gt 1) (choice lt 4))
System.out.println("\nSize " thing.size())
System.out.println("Personality "
thing.personality()) System.out.println("
Category " thing.category())
System.out.println("Sound " thing.sound()
"\n") //if while ((choice gt 1)
(choice lt 4)) //main //Poly
34Polymorphism
public class Mammal public String category()
return "We all be Mammals..."
public String size() return "Unknown
mammal" public String personality()
return "Unknown mammal" public String
sound() return "Unknown mammal"
35Polymorphism
public class Dog extends Mammal public String
size() return "Medium to small"
public String personality() return
"Person's best friend" public String
sound() return "Barks loudly"
36Polymorphism
public class Mouse extends Mammal public
String size() return "Small"
public String personality() return "Scares
elephants" public String sound()
return "Squeak"
public class Lion extends Mammal public
String size() return "Large"
public String personality() return
"Ferocious" public String sound()
return "Hear me roar"
37Polymorphism
public class Horse extends Mammal public
String size() return "Very large"
public String personality() return "Beast
of burden" public String sound()
return "Neighs"
38Polymorphism
Which type of mammal do you want to be? 1.
Dog 2. Lion 3. Mouse 4. Horse Enter your
choice 1 Size Medium to small Personality
Person's best friend Category We all be
Mammals... Sound Barks loudly
39Polymorphism
Which type of mammal do you want to be? 1.
Dog 2. Lion 3. Mouse 4. Horse Enter your
choice 4 Size Very large Personality Beast of
burden Category We all be Mammals... Sound
Neighs
40final Methods and Classes
- Methods declared final
- cannot be overridden in a subclass
- static or private methods are implicitly final
- allows inlining the code
- Classes declared final
- cannot be a superclass
- all methods are implicitly final
41Abstract classes
- Declared abstract
- Cannot be instantiated
- Provides a superclass for other classes to
inherit from - If one or more methods in a class are declared to
be abstract, then the class must be declared
abstract
42Abstract Methods
- The modifiers final and static cannot be used
with abstract methods - Children must override the abstract methods of
the abstract parent - If dont override all abstract methods, the child
must be declared abstract - Somewhere in the hierarchy all abstract methods
need to be made concrete
43Printer Example
File
Binary_File
Text_File
Image_File
44Printer Example
public class Printer public static void
main (String args) byte logo_data
41, 42, 49, 44 Text_File report new
Text_File ("Sand Reconner", 66, "One
two three") Image_File logo new
Image_File ("Number 1", 45,
logo_data) Print_Logger
daily new Print_Logger()
daily.log(report) daily.log(logo)
// method main // class Printer
45Printer Example (contd)
abstract class File protected String id
protected int size public File (String
file_id, int file_size) id file_id
size file_size // constructor File
public String name() return id
// method name abstract public String
print() // class File
46Printer Example (contd)
class Text_File extends File protected
String text public Text_File (String id, int
size, String file_contents) super(id,
size) text file_contents
//constructor Text_File public String
print() return text // print
method // class Text_File
47Printer Example (contd)
class Binary_File extends File protected
byte data public Binary_File (String
id, int size, byte file_data)
super(id, size) data file_data
//constructor Binary_File public String
print() return "" //method
print // class Binary_File
48Printer Example (contd)
class Image_File extends Binary_File
public Image_File (String id, int size, byte
file_data) super(id, size, file_data)
// constructor Image_File public
String print() return new String
(data) //method print //class Image_File
49Printer Example (contd)
class Print_Logger public void log (File
file) System.out.println (file.name()
" " file.print()) // method
log //class Print_Logger
50Printer Example Output
51Abstract Classes
Crust
Toppings
Traditional
Deep Dish
Mushroom
Sausage
Cheese
52Interfaces
- Collection of constants and abstract methods
- Not classes
- Can be used in the definition of a class
- interface interface-name constants and methods
- class class-name implements interface-name
implementation of abstract methods
53Interfaces
- All methods in an interface are, by default,
public and abstract - All constants are public and final
- Constants can be used in the class as if they
were declared locally - Interfaces can be linked in a hierarchy (extends)
like classes
54Interfaces
- Interface names can be used as a class type in
a formal parameter - Any class that implements that interface will be
accepted as the actual parameter - A class can implement more than one interface
- Interfaces allow for multiple inheritance
55Printer2 Example
public class Printer2 public static void
main (String args) byte logo_data
41, 42, 49, 44 Printable report new
Text_File ("Sand Reconner", 66, "One
two three") Printable logo new
Image_File ("Number 1", 45,
logo_data) Print_Logger
daily new Print_Logger()
daily.log(report) daily.log(logo) //
method main // class Printer2
56Printer2 Example
class File protected String id
protected int size public File (String
file_id, int file_size) id file_id
size file_size // constructor File
public String name() return id
// method name // class File
No Print() method Not abstract any longer
57Printer2 Example
class Text_File extends File implements Printable
protected String text public Text_File
(String id, int size, String file_contents)
super(id, size) text
file_contents //constructor Text_File
public String print() return text
// print method // class Text_File
Implements the print() method name() method in
File
58Printer2 Example
class Binary_File extends File protected
byte data public Binary_File (String
id, int size, byte file_data)
super(id, size) data file_data
//constructor Binary_File // class
Binary_File
Doesnt implement Printable Parent to Image_File
59Printer2 Example
class Image_File extends Binary_File implements
Printable public Image_File (String
id, int size, byte file_data)
super(id, size, file_data) // constructor
Image_File public String print()
return new String (data) //method
print //class Image_File
Implements print() name() in File class
60Printer2 Example
interface Printable String name()
String print() // interface
Printable class Print_Logger public void
log (Printable file) System.out.println
(file.name() " " file.print()) //
method log //class Print_Logger
Names name() and print() methods to be implemented
interface Name
61Printer2 Example Output
62Abstract Classes and Interfaces
- Used together become a powerful tool
- Multiple Inheritance
- Encapsulate and hide information
- Specify what must be done not how
- Allow systems to be built by many programmers
- Basically, represent the heart of object
orientation
63PizzaPlace
interface Costable double cost() //interfac
e Costable class Coster public double
cost(Costable c) return c.cost() //
method cost // class Coster
64PizzaPlace
class Pizza private Toppings toppings
private Crust crust private Sauce
sauce Pizza (Crust c, Sauce s, Toppings
t) toppings t crust
c sauce s //constructor
public int time() return
(toppings.time() crust.time() sauce.time())
//time public double cost()
Coster coster new Coster()
return (coster.cost(toppings)
coster.cost(crust)
coster.cost(sauce)) //class Pizza
65PizzaPlace
abstract class Crust implements Costable
abstract public int time() //class Crust
66PizzaPlace
class DeepDish extends Crust public int time
() return 15 public double
cost() return 4.50
//DeepDish class Traditional extends Crust
public int time () return 13
public double cost() return 4.00
//Traditional
class Thin extends Crust public int time ()
return 10 public double cost()
return 4.00 //Thin
67PizzaPlace
class Red extends Sauce public int time ()
return 6 public double cost()
return 2.00 //Red class White
extends Sauce public int time ()
return 5 public double cost()
return 2.30 //White
abstract class Sauce implements Costable
abstract public int time() //class Sauce
68PizzaPlace
class Toppings implements Costable private
Vector tops new Vector() public void
addTopping(Topping top)
tops.addElement(top) // public int
time() int total 0 for (int i
0 i lt tops.size() i) total
((Topping)tops.elementAt(i)).time()
return total public double cost()
Coster coster new Coster()
double total 0 for (int i 0 i lt
tops.size() i) total
coster.cost((Topping)tops.elementAt(i))
return total //class Toppings
69PizzaPlace
class Sausage extends Topping public int
time() return 7 public double
cost() return 1.50 //Sausage class
Anchovy extends Topping public int time()
return 4 public double cost()
return 2.25 //Anchovy
abstract class Topping implements Costable
abstract public int time() //Class
Topping class Cheese extends Topping public
int time() return 5 public
double cost() return 1.25 //Cheese
70PizzaPlace
import java.io. import java.util. class
PizzaPlace public static void main
(String args) throws IOException
BufferedReader stdin new BufferedReader
(new InputStreamReader(System.in), 1)
String response null, again "n"
Crust crust null Sauce sauce null
71PizzaPlace
do Toppings top new
Toppings() do
System.out.println("Enter the number of the crust
you want\n") System.out.println(" 1.
Traditional") System.out.println("
2. Deep Dish") System.out.println("
3. Thin") response
stdin.readLine() switch
(response.charAt(0)) case '1'
crust new Traditional()
break case '2'
crust new DeepDish()
break case '3'
crust new Thin() break
default
System.out.println("\nPlease make a valid
choice") //switch while
(response.charAt(0) lt '1' response.charAt(0) gt
'3')
72PizzaPlace
do System.out.println("Enter
the number of the sauce you want\n")
System.out.println(" 1. Red")
System.out.println(" 2. White")
response stdin.readLine() switch
(response.charAt(0)) case '1'
sauce new Red()
break case '2'
sauce new White() break
default
System.out.println("\nPlease make a valid
choice") //switch while
(response.charAt(0) lt '1' response.charAt(0) gt
'2')
73PizzaPlace
String repeat "n" do
do System.out.println("Enter the
number of the topping you want\n")
System.out.println(" 1. Cheese")
System.out.println(" 2. Sausage")
System.out.println(" 3. Anchovy")
response stdin.readLine()
74PizzaPlace
switch (response.charAt(0))
case '1' Cheese cheese new
Cheese() top.addTopping(cheese)
break case '2'
Sausage sausage new Sausage()
top.addTopping(sausage)
break case '3'
Anchovy anchovy new Anchovy()
top.addTopping(anchovy)
break default
System.out.println("\nPlease make a valid
choice") //switch while
(response.charAt(0) lt '1' response.charAt(0) gt
'3') System.out.print("\nDo you want
another topping (Y or N))? ") repeat
stdin.readLine() while
(repeat.equals("y") repeat.equals("Y"))
75PizzaPlace
Pizza pizza new Pizza(crust, sauce,
top) System.out.println("\nBaking time for
your pizza is " pizza.time())
System.out.println("\nTotal cost for your pizza
is " pizza.cost()) System.out.print("\nD
o you want to order another pizza (Y or N)? ")
again stdin.readLine() while
(again.equals("y") again.equals("Y"))
//main method //class PizzaPlace
76PizzaPlace
Enter the number of the crust you want 1.
Traditional 2. Deep Dish 3. Thin 1 Enter the
number of the sauce you want 1. Red 2.
White 1 Enter the number of the topping you
want 1. Cheese 2. Sausage 3. Anchovy 1 Do
you want another topping (Y or N))?
77PizzaPlace
Do you want another topping (Y or N))? n Baking
time for your pizza is 24 Total cost for your
pizza is 7.25 Do you want to order another
pizza (Y or N)?
78Inner Classes
- Classes defined within the scope of another class
- Can be complete class definitions
- Can be anonymous classes
- Used mainly in event handling
- Can access all instance variables and methods of
the outer class - If defined in a method, limited access to
variables
79InnerClasses.java
class Outer private int count private
String name public Outer(String n, int c)
count c name n class Inner
public void printIt()
System.out.println("Name " name "
Count " count) // Inner
Class //Outer Class
80TestOuter.java
class TestOuter public static void main
(String args) Outer o new
Outer("Komar", 5) Outer.Inner oi o.new
Inner() oi.printIt()
81Output
D\QM281\examplesgtjava TestOuter Name Komar
Count 5
82Files
OUTER1 CLA 545 01-14-00 915a
Outer.class INNERC1 JAV 306 01-14-00
915a InnerClasses.java OUTER2 CLA
871 01-14-00 915a OuterInner.class TESTOU1
CLA 464 01-14-00 914a
TestOuter.class TESTOU1 JAV 174
01-14-00 914a TestOuter.java
83Anonymous Inner Classes
minuteField.addActionListener( new
ActionListener() // anonymous inner class
public void actionPerformed( ActionEvent e
) t.setMinute(
Integer.parseInt( e.getActionCommand()
) ) minuteField.setText( "" )
displayTime()
)
Generates a classNamen .class file
84Wrapper Classes
- Object classes for the primitive data types
- Character, Byte, Short, Integer, Long, Float,
Double, and Boolean - Allow for polymorphic handling of primitive data
types wrapped in their Wrapper classes
85Summary
- Inheritance
- Constructors and Finalizers
- Composition versus Inheritance
- Polymorphism
- final Methods and Classes
- Interfaces
- Inner Classes
- Wrapper Classes