Slides08 - Munoz AHISD

advertisement
Object Oriented Programming (OOP) is a style of
programming that incorporates these 3 features:
Encapsulation
Polymorphism
Class Interaction
Object Oriented Programming simulates real life
by using a program style that treats a program
as a group of objects.
Object Oriented Programming one of the main
reasons we now teach Java instead of C++.
C++ was designed to be backwardly compatible
with the original (non-OOP) C programming
language. Therefore in C++, OOP is optional.
In Java OOP is required. The College Board
wants students to learn OOP so Java it is.
OOP
Example
A car could be an object in Java.
Objects have attributes and methods.
Car Attributes
Car Methods
Make & Model
Drive
Color
Park
# of Doors
Reverse
# of Seats
Tow
Encapsulation
Car Attributes
Car Methods
Make & Model
Drive
Color
Park
# of Doors
Reverse
# of Seats
Tow
Encapsulation means packaging or
encapsulating all of the attributes and
methods of an object in the same container.
Polymorphism
If we review our Algebra we should remember:
A monomial is a single term like: 3x
A binomial is 2 terms like: 3x + 7
A polynomial is many terms like: x2 + 3x + 7
The prefix Poly means many.
Polymorphism means many forms.
Polymorphism is an advanced concept in
computer science which will be discussed
in AP Computer Science. To attempt to
explain it now will only cause confusion.
Class Interaction - Inheritance
There are different types of Class Interaction. One type is Inheritance.
Suppose you wish to create Truck objects, Limo objects and Racecar
objects. Instead of starting each from scratch we can use the existing
Car in the following manner:
A Truck is a Car with 4WD, big tires, and a bed.
A Limo is a very long luxury Car with many seats.
A Racecar is a Car with 1 seat, a very powerful
engine, and a number painted on the side.
Inheritance will be discussed in Chapter 9.
The 4 Stages of
Program Design

Cryptic Programming Stage

Unstructured,
Spaghetti-Programming Stage

Structured Programming Stage

Object Oriented Programming Stage
Avoid Spaghetti Programming
Program Statement
Program Statement
Program Statement
Program Statement
Program Statement
Program Statement
Program Statement
Program Statement
Back to Encapsulation
Java encapsulates data and action modules
that access the data in one container, called
an object.
Object members that perform some task are
called methods.
Object members that store data are called
attributes.
Normal “Non-OOP” Airport
In a normal airport, the following places are
scattered all over the airport.
•
•
•
•
•
Curb-Side Check-In
Security
Departure Gates
Arrival Gates
Baggage claim
The same gates are used for the arrival and
departure of different planes to different places.
“OOP-ified” Airport
An airport would never be designed this way, but if
they followed the encapsulation concept of OOP,
you would have the following Destination objects:
class Destination
object Paris
class Destination
object Amsterdam
Methods:
Check-In
Security
Gates
Methods:
Check-In
Security
Gates
// Java0801.java
// Stage #1 of the <Bank> class
// The only thing that is done in this stage is the creation of a container.
// It is the "container" or "block" or officially the "class" which will be the
// toolkit for all the different tool necessary to handle bank transactions.
// This <Bank> class is minimal program code. It does nothing, but it will compile.
// The <Java0801> class contains the <main> method used to test our user-created class.
public class Java0801
{
public static void main(String args[])
{
System.out.println("\nJAVA0801.JAVA\n");
}
}
class Bank
{
}
//
//
//
//
//
The class heading of the <Bank> class
The opening brace of the <Bank> container
All elements of the <Bank> must be placed
between the braces
The closing brace of the <Bank> container
// Java0802.java
// Stage #2 of the <Bank> class
// In the second stage the main method creates a <Bank> object,
// called <tom>. Java does not complain.
// A pretty much useless <tom> object is created.
public class Java0802
{
public static void main(String args[])
{
System.out.println("\nJAVA0802.JAVA\n");
Bank tom = new Bank();
}
}
class Bank
{
}
//
Java0803.java
The
way this program is
// Stage #3 of the <Bank> class
written,
nothing prevents
// This program may seem logical. Values are assigned to program variables.
Tom
from
changing
histhe <tom> class container.
// The data
variables
are inside
//
The object.identifier
syntax seems
balances
to $1,000,000
or as it was shown in previous chapters.
//////////// THIS IS BAD OLD-STYLE PROGRAMMING //////////
more. Nothing prevents
public class Java0803
someone
else from
{
public static
main(String
args[])
changing
it tovoid
$0.00
as well.
{
System.out.println("\nJAVA0803.JAVA\n");
Bank tom = new Bank();
tom.checkingBal = 1000.00;
tom.savingsBal = 3000.00;
System.out.println("Checking Balance: " + tom.checkingBal);
System.out.println("Savings Balance: " + tom.savingsBal);
System.out.println("\n\n");
}
}
class Bank
{
double checkingBal;
double savingsBal;
}
// data attribute to store the object's checking balance
// data attribute to store the object's savings balance
// Java0804.java
// Stage #4 of the <Bank> class
// This protects the checking and savings balances from
// outside alteration by making them private attributes.
public class Java0804
{
public static void main(String args[])
{
System.out.println("\nJAVA0804.JAVA\n");
Bank tom = new Bank();
tom.checkingBal = 1000.00;
tom.savingsBal = 3000.00;
System.out.println("Checking Balance: " + tom.checkingBal);
System.out.println("Savings Balance: " + tom.savingsBal);
System.out.println("\n\n");
}
}
class Bank
{
private double checkingBal; // data attribute to store the object's checking balance
private double savingsBal;
// data attribute to store the object's savings balance
}
private & public Members
Members in a class need to be declared as
private or public.
private members cannot be accessed by any
program segments outside the class.
public members of a class can be accessed by
program segments outside the class.
Class attributes are usually declared private.
Class methods are usually declared public.
“Mr. Schram, how does using
private give you any
security when you can just
change it back to public?”
Think of any video game that you
have ever purchased.
Do you ever see the source code?
Only the programmers have the source code.
What they sell to users is an executable file.
// Java0805.java
// Stage #5 of the <Bank> class
// This stage adds a "constructor" method, which initializes the both balances to zero.
// The constructor is automatically called when the new object (line 12) is constructed.
// There is no output, because data is assigned, but not displayed.
public class Java0805
{
public static void main(String args[])
{
System.out.println("\nJAVA0805.JAVA\n");
Bank tom = new Bank();
System.out.println("\n\n");
}
}
class Bank
{
// The attributes (data variables) are usually listed first inside the class container.
private double checkingBal;
private double savingsBal;
// The methods (modules that process attributes) usually start with the constructor.
// The constructor has the same name as the class and initializes the data variables.
public Bank()
{
checkingBal = 0.0;
savingsBal = 0.0;
}
}
“Mr. Schram, couldn’t we
just create an intializeData
method instead of using a
constructor ?
You could, but it would not be as reliable.
It is possible that you would forget
to call this initializeData method.
A constructor is more reliable because you
cannot forget to call a constructor.
It is called automatically.
Instantiation & Construction
A class is a template that can form many objects.
An object is a single variable instance of a class.
Objects are sometimes called instances.
An object is created with the new operator.
The creation of a new object is called:
instantiation of an object
construction of an object
The special method that is called during the
instantiation of a new object is the constructor.
// Java0806.java Stage #6 of the <Bank> class
// Two methods are added to access the attribute values for public use.
// It is now possible to see the balances of the bank account.
public class Java0806
{
public static void main(String args[])
{
System.out.println("\nJAVA0806.JAVA\n");
Bank tom = new Bank();
System.out.println("Checking Balance: " + tom.getChecking());
System.out.println("Savings Balance: " + tom.getSavings());
System.out.println("\n\n");
}
}
class Bank
{
private double checkingBal;
private double savingsBal;
// The methods (modules that process attributes) usually start with the constructor.
// The constructor has the same name as the class and initializes the data variables.
public Bank() { checkingBal = 0.0; savingsBal = 0.0; }
// The next two methods are "read-only" methods that return private data values.
// Such methods are traditionally called "get methods" and "get" is often in the name.
public double getChecking() { return checkingBal; }
public double getSavings()
{ return savingsBal; }
}
Object Methods a.k.a.
Non-Static Methods
The key difference between defining a class
(static) method and an object (non-static) method
is the keyword static.
Object methods do not have the
keyword static in their heading.
public double getChecking() { return checkingBal; }
public double getSavings()
{ return savingsBal;
}
// Java0807.java Stage #7 of the <Bank> class
// This stage demonstrates how to create an "overloaded" method. The 2nd constructor has the same
// identifier as the 1st constructor. However, the second constructor has a different heading signature.
// Java knows which method to use by checking the parameters. A 2nd constructor allows user-input
// for the constructor. This program also shows that is it possible to have two bank accounts.
// This is only possible with a class that has object methods.
public class Java0807
{
public static void main(String args[])
{
System.out.println("\nJAVA0807.JAVA\n");
Bank tom = new Bank();
Bank sue = new Bank(2000.0,2000.0);
System.out.println("Tom's Checking Balance: " + tom.getChecking());
System.out.println("Tom's Savings Balance: " + tom.getSavings());
System.out.println();
System.out.println("Sue's Checking Balance: " + sue.getChecking());
System.out.println("Sue's Savings Balance:
" + sue.getSavings());
System.out.println("\n\n");
}
}
class Bank
{
/////////// ATTRIBUTES //////////
private double checkingBal;
private double savingsBal;
////////// CONSTRUCTOR METHODS //////////
public Bank() { checkingBal = 0.0; savingsBal = 0.0; }
public Bank(double cBal, double sBal) { checkingBal = cBal; savingsBal = sBal; }
}
// Java0807.java Stage #7 of the <Bank> class
// This stage demonstrates how to create an "overloaded" method. The 2nd constructor has the same
// identifier as the 1st constructor. However, the second constructor has a different heading signature.
// Java knows which method to use by checking the parameters. A 2nd constructor allows user-input
// for the constructor. This program also shows that is it possible to have two bank accounts.
// This is only possible with a class that has object methods.
public class Java0807
{
public static void main(String args[])
{
System.out.println("\nJAVA0807.JAVA\n");
Bank tom = new Bank();
Bank sue = new Bank(2000.0,2000.0);
System.out.println("Tom's Checking Balance:
System.out.println("Tom's Savings Balance:
System.out.println();
System.out.println("Sue's Checking Balance:
System.out.println("Sue's Savings Balance:
System.out.println("\n\n");
" + tom.getChecking());
" + tom.getSavings());
" + sue.getChecking());
" + sue.getSavings());
}
}
class Bank
{
/////////// ATTRIBUTES //////////
private double checkingBal;
private double savingsBal;
////////// CONSTRUCTOR METHODS //////////
public Bank() { checkingBal = 0.0; savingsBal = 0.0; }
public Bank(double cBal, double sBal) { checkingBal = cBal; savingsBal = sBal; }
}
// Java0807.java Stage #7 of the <Bank> class
// This stage demonstrates how to create an "overloaded" method. The 2nd constructor has the same
// identifier as the 1st constructor. However, the second constructor has a different heading signature.
// Java knows which method to use by checking the parameters. A 2nd constructor allows user-input
// for the constructor. This program also shows that is it possible to have two bank accounts.
// This is only possible with a class that has object methods.
public class Java0807
{
public static void main(String args[])
{
System.out.println("\nJAVA0807.JAVA\n");
Bank tom = new Bank();
Bank sue = new Bank(2000.0,2000.0);
System.out.println("Tom's Checking Balance:
System.out.println("Tom's Savings Balance:
System.out.println();
System.out.println("Sue's Checking Balance:
System.out.println("Sue's Savings Balance:
System.out.println("\n\n");
" + tom.getChecking());
" + tom.getSavings());
" + sue.getChecking());
" + sue.getSavings());
}
}
class Bank
{
/////////// ATTRIBUTES //////////
private double checkingBal;
private double savingsBal;
////////// CONSTRUCTOR METHODS //////////
public Bank() { checkingBal = 0.0; savingsBal = 0.0; }
public Bank(double cBal, double sBal) { checkingBal = cBal; savingsBal = sBal; }
}
// Java0807.java Stage #7 of the <Bank> class
// This stage demonstrates how to create an "overloaded" method. The 2nd constructor has the same
// identifier as the 1st constructor. However, the second constructor has a different heading signature.
// Java knows which method to use by checking the parameters. A 2nd constructor allows user-input
// for the constructor. This program also shows that is it possible to have two bank accounts.
// This is only possible with a class that has object methods.
public class Java0807
{
public static void main(String args[])
{
System.out.println("\nJAVA0807.JAVA\n");
Bank tom = new Bank();
Bank sue = new Bank(2000.0,2000.0);
System.out.println("Tom's Checking Balance: " + tom.getChecking());
System.out.println("Tom's Savings Balance: " + tom.getSavings());
System.out.println();
System.out.println("Sue's Checking Balance: " + sue.getChecking());
System.out.println("Sue's Savings Balance:
" + sue.getSavings());
System.out.println("\n\n");
}
}
class Bank
{
/////////// ATTRIBUTES //////////
private double checkingBal;
private double savingsBal;
////////// CONSTRUCTOR METHODS //////////
public Bank() { checkingBal = 0.0; savingsBal = 0.0; }
public Bank(double cBal, double sBal) { checkingBal = cBal; savingsBal = sBal; }
}
Constructor Notes
Constructors are methods, which are called during the
instantiation of an object with the new operator.
The primary purpose of a constructor is to
initialize all the attributes of newly created object.
Constructors have the same identifier as the class.
Constructors are neither void methods nor are they
return methods. They are simply constructors.
Constructors are always declared public.
Constructors can be overloaded methods.
The method identifier can be the same, but the method
signature (which is the parameter list) must be different.
A constructor with no parameters
is called a default constructor.
// Java0808.java Stage #8 of the <Bank> class
// Two methods are added that can read/write the attributes.
// These are methods that make deposits to the checking and savings accounts.
public class Java0808
{
public static void main(String args[])
{
System.out.println("\nJAVA0808.JAVA\n");
Bank tom = new Bank(1000.0,3000.0);
Bank sue = new Bank(2000.0,2000.0);
tom.checkingDeposit(1000.0);
sue.savingsDeposit(2500.0);
System.out.println("Tom's Checking Balance:
System.out.println("Tom's Savings Balance:
System.out.println();
System.out.println("Sue's Checking Balance:
System.out.println("Sue's Savings Balance:
System.out.println("\n\n");
}
}
" + tom.getChecking());
" + tom.getSavings());
" + sue.getChecking());
" + sue.getSavings());
class Bank
{
////////// SET or MUTATOR "READ/WRITE" METHODS //////////
public void checkingDeposit(double amount) { checkingBal += amount; }
public void savingsDeposit(double amount)
}
{ savingsBal += amount; }
// Java0809.java Stage #9 of the <Bank> class
// Two more methods are added that can read/write the attributes.
// These are methods that make withdrawals from the checking and savings accounts.
// Note that the withdrawal methods have no protection against taking out more money than you have.
public class Java0809
{
public static void main(String args[])
{
System.out.println("\nJAVA0809.JAVA\n");
Bank tom = new Bank(1000.0,3000.0);
Bank sue = new Bank(2000.0,2000.0);
tom.savingsWithdrawal(2500.0);
sue.checkingWithdrawal(2500.0);
System.out.println("Tom's Checking Balance: " + tom.getChecking());
System.out.println("Tom's Savings Balance: " + tom.getSavings());
System.out.println();
System.out.println("Sue's Checking Balance: " + sue.getChecking());
System.out.println("Sue's Savings Balance: " + sue.getSavings());
System.out.println("\n\n");
}
}
class Bank
{
public void checkingWithdrawal(double amount)
public void savingsWithdrawal(double amount)
}
{ checkingBal -= amount; }
{ savingsBal -= amount; }
// Java0810.java Stage #10 of the <Bank> class
// The withdrawal methods now protect against overdraft. Some extra printlns are added for clarification.
public class Java0810
{
public static void main(String args[])
{
System.out.println("\nJAVA0809a.JAVA\n");
Bank tom = new Bank(1000.0,3000.0);
Bank sue = new Bank(2000.0,2000.0);
System.out.println("Tom asks the teller to withdraw $2500 from his savings account.");
tom.savingsWithdrawal(2500.0);
System.out.println("Sue asks the teller to withdraw $2500 from her checking account.");
sue.checkingWithdrawal(2500.0);
System.out.println("Tom's Checking Balance: " + tom.getChecking());
System.out.println("Tom's Savings Balance: " + tom.getSavings());
System.out.println();
System.out.println("Sue's Checking Balance: " + sue.getChecking());
System.out.println("Sue's Savings Balance: " + sue.getSavings());
System.out.println("\n\n");
}
}
class Bank
{
public void checkingWithdrawal(double amount)
{
if (amount > checkingBal)
System.out.println("Insufficient Funds! Transaction Refused!\n");
else
checkingBal -= amount;
}
public void savingsWithdrawal(double amount)
{
if (amount > savingsBal)
System.out.println("Insufficient Funds! Transaction Refused!\n");
else
savingsBal -= amount;
}
}
// Java0811.java Stage #11 of the <Bank> class
// The final stage of the <Bank> removes the class from the <Java0810.java> file
// and creates a separate file, called Bank.java.
public class Java0811
{
public static void main(String args[])
{
System.out.println("\nJAVA0811.JAVA\n");
Bank tom = new Bank(1000.0,3000.0);
Bank sue = new Bank(2000.0,2000.0);
tom.checkingWithdrawal(500.0);
sue.savingsWithdrawal(800.0);
System.out.println("Tom's Checking Balance:
System.out.println("Tom's Savings Balance:
System.out.println();
System.out.println("Sue's Checking Balance:
System.out.println("Sue's Savings Balance:
System.out.println("\n\n");
}
}
" + tom.getChecking());
" + tom.getSavings());
" + sue.getChecking());
" + sue.getSavings());
// Bank.java
Stage #11 of the <Bank> class
// The <Bank> is now placed in its own file, which is better program design.
// You must now declare the class as "public".
public class Bank
{
}
/////////// ATTRIBUTES //////////
private double checkingBal;
private double savingsBal;
////////// CONSTRUCTOR METHODS //////////
public Bank() { checkingBal = 0.0; savingsBal = 0.0; }
public Bank(double cBal, double sBal) { checkingBal = cBal; savingsBal = sBal; }
////////// GET "READ-ONLY" METHODS //////////
public double getChecking() { return checkingBal; }
public double getSavings()
{ return savingsBal;
}
////////// SET or MUTATOR "READ/WRITE" METHODS //////////
public void checkingDeposit(double amount) { checkingBal += amount; }
public void savingsDeposit(double amount)
{ savingsBal += amount; }
public void checkingWithdrawal(double amount)
{
if (amount > checkingBal)
System.out.println("Insufficient Funds! Transaction Refused!\n");
else
checkingBal -= amount;
}
public void savingsWithdrawal(double amount)
{
if (amount > savingsBal)
System.out.println("Insufficient Funds! Transaction Refused!\n");
else
savingsBal -= amount;
}
Classes in Separate Files
The previous program works because the
Bank.java is located in the same folder as
Java0811.java. It is very common to put each
class in its own file.
This is also the same reason
why the Expo.java file is
located in the folder as well.
Java0811.java
Bank.java
Expo.java
Way back in Chapter 2, you were told the name of
the file must always match the name of the class.
This is the reason why. If they did not match a file
would not be able to find a class in another file.
Class or Static Methods
Class methods are sometimes called static
methods because they have the keyword static
in their heading.
A class method is called with the class identifier,
not with an object of the class.
This is practical when there is no need to make
multiple objects of a class.
A good example is Java’s Math class.
Class or Static Methods
public class Demo
{
public static void main(String args[])
{
Piggy.initData();
Piggy.showData();
Piggy.addData(1200);
Piggy.showData();
}
}
class Piggy
{
public static double savings;
public static void initData()
{ savings = 0; }
public static void addData(double s)
{ savings += s; }
public static void showData() { System.out.println("Savings: " + savings); }
}
Object or Non-Static Methods
Object methods are sometimes called non-static
methods because they do NOT have the keyword
static in their heading.
Object methods are meant for those situations
where multiple objects of a class must be
constructed.
An object must be constructed first with the new
operator, and then object methods are called by
using the object identifier.
Object or Non-Static Methods
public class Demo
{
public static void main(String args[])
{
Piggy tom = new Piggy();
tom.initData();
tom.showData();
tom.addData(1200);
tom.showData();
}
}
class Piggy
{
private double savings;
public void initData()
{ savings = 0;
}
public void addData(double s) { savings += s; }
public void showData() { System.out.println("Savings: " + savings);
}
}
Public Methods
Essentially, public methods
can be accessed anywhere.
The majority of methods are public.
public int getCards()
{
return cardsLeft;
}
Private or Helper Methods
Occasionally, a method is created in a class that
is never called outside of the class.
In such a case, the method
should be declared private.
These private methods are sometimes called
helper methods because they help and support
the other methods of the class.
Void Methods
Void methods do NOT return a value and use the
reserved word void to indicate that no value will
be returned.
public void showData()
{
System.out.println("Name: " + name);
System.out.println("Savings: " + savings);
}
Return Methods
Return methods are methods that return a value.
Two features are necessary for a return method:
First, you will see that the method heading indicates a
data type, which is the type that the method returns.
Second, you see a return statement at the end of the
method body.
public double getSavings()
{
return savings;
}
Default Constructor Methods
A constructor is a special method that is
automatically called during the instantiation
of a new object.
If no visible constructor is provided, Java will
provide its own constructor, called a
default constructor.
public CardDeck()
{
Additionally, we also call a
no-parameter constructor
a default constructor.
numDecks = 1;
numPlayers = 1;
cardsLeft = 52;
shuffleCards();
}
Overloaded Constructor Methods
An overloaded constructor is a second, third or
more, constructor that allows a new object to be
instantiated according to some specifications
that are passed by parameters.
public CardDeck(int d, int p)
{
numDecks = d;
numPlayers = p;
cardsLeft = d * 52;
shuffleCards();
}
Accessing or Get Methods
Methods that only access object data without
altering the data are called accessing or get
methods.
Most accessing methods are return methods,
which return object private data information.
public int getDecks()
{
return numDecks;
}
Altering or Modifier or
Mutator or Set Methods
These are methods that not
only access the private data of
an object; they also alter the
value of the data.
public void savingsDeposit(double s)
{
savings += s;
}
Download