Professional Documents
Culture Documents
contd
Polymorphism, pt 1
COMP 401, Fall 2016
Lecture 07
9/15/2016
Encapsula)on In Prac)ce
Part 2: Separate Exposed Behavior
Dene an interface for all exposed behavior
In Java, an interface is like a contract.
Indicates that a certain set of public methods are available.
One or more classes can indicate that they implement the
interface.
Interfaces in Java
Like classes, should go in their own .java le
Form:
Conven)on B
Programming To An Interface
lec6.v6
Separates Point into an interface and an implemen)ng
class.
Advantage of Encapsula)on
Can provide dierent implementa)ons of the
same behavior
lec6.v7
Create a new implementa)on of Point based on polar
coordinates.
lec6.v8
Con)nued applica)on of encapsula)on
principle to Triangle by
dening Triangle as an interface
rewri)ng what used to be the class Triangle as
the class PointTriangle that implements the
interface
hiding internal behaviors as private methods
Summing Up
A Java le denes one public class or public
interface.
To support encapsula)on:
Polymorphism
Poly = many, morph = forms
General principle of providing access to an
abstrac)on or method in many forms
Idea is that dierent forms t dierent contexts
Goal of the underlying func)onality is the same.
Constructors
What happens when you dont dene a
constructor.
Default constructor with no arguments.
Creates new object with all elds set to default value
Numeric elds set to 0
Boolean elds set to false
String, Array, and any other sort of reference value eld set to
null.
lec7.ex1
Constructor Overloading
Can dene mul)ple versions of the constructor.
Dis)nguished from each other by type and number of
parameters
Must be some dierence otherwise the compiler wont be
able to tell them apart.
lec7.ex2
Constructor Chaining
Common padern is to chain one constructor o
of another.
To do this, the rst line of code in the constructor
must be the this keyword used as if a func)on with
parameters.
The matching constructor is called rst and allowed to
execute.
Then any subsequent code is executed.
Can chain mul)ple constructors one on to another
lec7.ex3