Object-Oriented Programming sides face roll getFace getSides.
-
date post
21-Dec-2015 -
Category
Documents
-
view
224 -
download
1
Transcript of Object-Oriented Programming sides face roll getFace getSides.
Object-Oriented Programming
Problem solving approach that focuses on describing the participating entities in the problem domain and the
interactions between them.
Object-Oriented Programming
The four key concepts:
classes and objects
encapsulation
inheritance
polymorphism
Classes and Objects
class – abstract description of the properties and behavior of an entity
object – concrete instance of a class
properties (data members) – what an object “knows”
behavior (methods) – what an object “can do”
Classes and Objects
Designing a Die class:
A die “knows”: how many sides it has which face is currently up
A die “can do”: report its number of sides report which face is up roll so a new face is up
sides
face
roll
getFacegetS
ides
Encapsulation
encapsulate – “1.to place in or as if in a capsule.” (merriam-webster.com)
In OOP encapsulation refers to:
keeping together the data and the methods that manipulate the data
hiding the details of representation
Encapsulation
In Java encapsulation is afforded by:
keeping together the data and the methods that manipulate the data
class Die
{
// data members and methods go here
}
hiding the details of representation
public vs private access
Classes and Objects
Designing a Die class:
A die “knows”: how many sides it has which face is currently up
A die “can do”: report its number of sides report which face is up roll so a new face is up
sides
face
roll
getFacegetS
ides
class Die{ private int sides; private int face;
public Die() { // construct default die }
public Die(int s) { // construct die with given sides }
public int getSides() {
// report back number of sides }
public int getFace() { // report back face value }
public void roll() {
// set face value to random number }}
methods(behavior)
data members(properties)
class Die{ private int sides; private int face;
public Die() { // construct default die }
public Die(int s) { // construct die with given sides }
public int getSides() {
// report back number of sides }
public int getFace() { // report back face value }
public void roll() {
// set face value to random number }}
class Die{ private int sides; private int face;
public Die() { sides = 6; face = 1; }
public Die(int s) { sides = s; face = 1; }
public int getSides() {
return sides; }
public int getFace() { return face; }
public void roll() {
face = new Random().nextInt(sides) + 1; }}
class Die{ private int sides; private int face;
public Die() { sides = 6; face = new Random().nextInt(sides) + 1; }
public Die(int s) { sides = s; face = new Random().nextInt(sides) + 1; }
public int getSides() {
return sides; }
public int getFace() { return face; }
public void roll() {
face = new Random().nextInt(sides) + 1; }}
class Die{ private int sides; private int face;
public Die() { sides = 6; roll(); }
public Die(int s) { sides = s; roll(); }
public int getSides() {
return sides; }
public int getFace() { return face; }
public void roll() {
face = new Random().nextInt(sides) + 1; }}
class Die{ private int sides; private int face;
public Die() { this(6); // call the other constructor }
public Die(int s) { sides = s; roll(); }
public int getSides() {
return sides; }
public int getFace() { return face; }
public void roll() {
face = new Random().nextInt(sides) + 1; }}
Classes and Objects (Key Points)
Public vs. Private acess: data members – always private; forbids direct access
methods – those used to interact with the objects public
those that have specialized function private
Constructors: create the object; put it in a consistent initial state must have the same name as the class do not have return type (not even void) can have multiple versions (the constructor that takes no parameters – default constructor)
Creating Objects
ClassName objectName = new Constructor(………);
Die red = new Die(10);
ArrayList<Integer> numbers = new ArrayList<Integer>();
Random rand = new Random();
Pet tom = new Cat(“Tom”, 2001);
class DieTester{ public static void main(String[] args) { Die red = new Die(); Die blue = new Die(10); Die green = new Die(10);
System.out.println(“red sides “ + red.getSides()); red.roll(); System.out.println(“red rolled “ + red.getFace());
System.out.println(“blue sides “ + blue.getSides()); blue.roll();
System.out.println(“blue rolled “ + blue.getFace());
System.out.println(“green sides “ + green.getSides()); green.roll();
System.out.println(“green rolled “ + green.getFace()); }}
Creating and Using Objects
sidesface
roll
getFace
getS
ides
sidesface
roll
getFace
getS
ides
sidesface
roll
getFace
getS
ides
Encapsulation (revisited)
Changing the Die representation:
original representation
int sides;
int face;
new representation
int[] dieData; // 1st cell – number of side
// 2nd cell – which face up
class Die{ private int[] dieData
public Die() { this(6); // call the other constructor }
public Die(int s) { dieData = new int[2]; dieData[0] = s; roll(); }
public int getSides() {
return dieData[0]; }
public int getFace() { return dieData[1]; }
public void roll() {
dieData[1] = new Random().nextInt(getSides()) + 1; }}
class DieTester{ public static void main(String[] args) { Die red = new Die(); Die blue = new Die(10); Die green = new Die(10);
System.out.println(“red sides “ + red.getSides()); red.roll(); System.out.println(“red rolled “ + red.getFace());
System.out.println(“blue sides “ + blue.getSides()); blue.roll();
System.out.println(“blue rolled “ + blue.getFace());
System.out.println(“green sides “ + green.getSides()); green.roll();
System.out.println(“green rolled “ + green.getFace()); }}
What Needs to Change?
sidesface
roll
getFace
getS
ides
sidesface
roll
getFace
getS
ides
sidesface
roll
getFace
getS
ides
Inheritance
creates hierarchies that capture the relationships among the entities in the system
promotes code-reuse -- pushing common code up the class hierarchy
affords polymorphism – treat uniformly objects from the class hierarchy
(via references/pointers of the base class)
Inheritance
Describing pets:
A pet “knows”: its name Its year of birth
A pet “can do”: report its name change its name report its birth year report its age report its human age speak
Not clear what to dofor a generic Pet!
Inheritance
Describing cats:
A cat “knows”: its name Its year of birth number of lives
A cat “can do”: report its name change its name report its birth year report its age report its human age speak report lives left
Describing dogs:
A dog “knows”: its name Its year of birth best friend
A dog “can do”: report its name change its name report its birth year report its age report its human age speak report best friend
Same forall Pets
Inheritance
Describing cats:
A cat “knows”: its name Its year of birth number of lives
A cat “can do”: report its name change its name report its birth year report its age report its human age speak report lives left
Describing dogs:
A dog “knows”: its name Its year of birth best friend
A dog “can do”: report its name change its name report its birth year report its age report its human age speak report best friend
Specific toCats/Dogs
class Pet{ private String name; private int birthYear;
public Pet(String n, int y) { name = n; birthYear = y; }
public String getName() { return name; }
public void setName(String newName) { name = newName; }
public int getBirthYear () {
return birthYear; }
public int getAge(int curYear) { return curYear – birthYear; }
// DON’T KNOW HOW TO COMPUTE public int getHumanAge(int curYear) {
return -1; }
// DON’T KNOW HOW TO SPEAK public void speak() { System.out.print(“Can’t speak”); }}
class Dog extends Pet{ private String friend;
public Dog(String n, int y, String f) { super(n, y); friend = f; }
public int getHumanAge(int curYear) { int age = getAge(curYear); return 7*age; }
public void speak() { System.out.println(getName() + “ says woof, woof!”); }
public String getFriendName() { return firend; }}
Inherit from Pet class
Call parent (Pet) constructor
Use my own methods inheritedfrom parent (Pet) class
Only Dogs can do this
class Cat extends Pet{ private int lives;
public Cat(String n, int y, int l) { super(n, y); lives = l; }
public int getHumanAge(int curYear) { int age = getAge(curYear); return 5*age; }
public void speak() { System.out.println(getName() + “ says meow!”); }
public int getNumLives() { return lives; }}
Inherit from Pet class
Call parent (Pet) constructor
Use my own methods inheritedfrom parent (Pet) class
Only Cats can do this
class PetTester{ public static void main(String[] args) { Pet generic = new Pet(“Generic”, 2000); Cat tom = new Cat(“Tom”, 2000, 9); Dog buddha = new Dog(“Buddha”, 2000, “Bailey”);
generic.speak(); // displays: Can’t speak tom.speak(); // displays: Tom says meow buddha.speak(); // displays: Buddha says woof, woof! S.o.p(“generic age “ + generic.getAge(2008)); // 8 S.o.p(“tom’s age “ + tom.getAge(2008)); // 8 S.o.p(“buddha’s age “ + buddha.getAge(2008)); // 8 S.o.p (“generic age “ + generic.getHumanAge(2008)); // -1 S.o.p(“tom’s age “ + tom.getHumanAge(2008)); // 40 S.o.p(“buddha’s age “ + buddha.getAge(2008)); // 56 }}
Inheritance
Inheritance Summary
parent/base class – the class from which we inherit
derived class – the class which inherits
super – reference to parent/base class
always call appropriate parent constructor – super(…)
only implement (override) methods for which parent does not provide adequate action
private members in parent not accessible in derived class
Polymorphism
polymorphims – many (poly) forms (morph)
refers to manipulating objects from derived classes through references/variables of the parent class
allows for greater flexibility in developing the code; new modules can be added easily to the system
(Easy to add new types of Actors to the GridWorld from Assignment 5 as long as they inherit directly from Actor or from Bug, Flower, Chameleon)
class PolyMorphism{ public static void main(String[] args) { Pet tom = new Cat(“Tom”, 2000, 9); // OK Pet buddha = new Dog(“Buddha”, 2000, “Bailey”); // OK
Cat c = new Pet(“Generic”, 2000); // ERROR Dog d = new Cat(“Sylvester”, 1990, 5); // ERROR }}
Polymorphism
class PolyMorphism{ public static void main(String[] args) { Pet tom = new Cat(“Tom”, 2000, 9); Pet buddha = new Dog(“Buddha”, 2000, “Bailey”);
tom.speak(); // displays: Tom says meow buddha.speak(); // displays: Buddha says woof, woof! S.o.p(“tom’s age “ + tom.getAge(2008)); // 8 S.o.p(“buddha’s age “ + buddha.getAge(2008)); // 8 S.o.p(“tom’s age “ + tom.getHumanAge(2008)); // 40 S.o.p(“buddha’s age “ + buddha.getAge(2008)); // 56 }}
Polymorphism
class PolyMorphism{ public static void main(String[] args) { ArrayList<Pet> pets = new ArrayList<Pet>();
Pet tom = new Cat(“Tom”, 2000, 9); Pet buddha = new Dog(“Buddha”, 2000, “Bailey”);
pets.add(tom); pets.add(buddha): pets.add(new Dog(“Bailey”, 2003, “Buddha”);
Cat sylv = new Cat(“Sylvester”, 1990, 5); pets.add(sylv);
for (int i = 0; i < pets.size(); i = i + 1) { Pet p = pets.get(i); p.speak(); p.getAge(2008); p.getHumanAge(2008); }}}
Polymorphism
class PolyMorphism{ public static void main(String[] args) { Grid<Actor> grid = new Grid<Actor>(20, 20); // 20x20 grid
Chameleon cham = new Chameleon(); grid.put(cham);
Flower rose = new Flower(); grid.put(rose);
Bug bug = new Bug(); grid.put(bug);
Actor flower = new Flower(); grid.put(flower);
Actor frog = new Frog(); grid.put(frog): }}
Polymorphism
Abstract Classes and Methods
abstract classes – when their purpose is to serve only as a base class in inheritance hierarchy
(Pet class is candidate for abstract: Pet objects cannot exist on their own since they can’t execute certain behaviors – getHumanAge(), speak())
abtract methods – methods for which the class cannot provide reasonable implementation
(The getHumanAge() and speak() methods in Pet class had no reasonable implementation.)
abstract class Pet{ private String name; private int birthYear;
public Pet(String n, int y) { name = n; birthYear = y; }
// // all methods with reasonable // implementation go here: // // getName, setName, getAge, getBirthYear //
// // methods without reasonable code made abstract //
public abstract int getHumanAge(int curYear);
public abstract void speak();}
class AbstractClasses{ public static void main(String[] args) {
Pet generic = new Pet(“Generic”, 2000); // ERROR
// generates compilation error: // Pet class is abstract – cannot create Pet objects }}
Abstract Classes and Methods
Static Data Members and Methods
static data members and methods – belong to the class as a whole
typical examples count how many objects of a class exist
constants – good candidates for making static
static methods CANNOT reference non-static members
non-static methods CAN reference static members
to access – ClassName.staticMember
Color.BLACK
Pet.getPetCount()
class StaticMembers{ public static void main(String[] args) { Cat tom = new Cat(“Tom”, 2000, 9); Pet sylv = new Cat(“Sylvester”, 1990, 5);
int totlCats = Cat.getCatCount(); System.out.println(“There are ” + totalCount + “ cats!”); // 2
Cat felix = new Cat(“Felix”, 1919, 3); totlCats = Cat.getCatCount(); System.out.println(“There are ” + totalCount + “ cats!”); // 3 }}
Static Data Members and Methods
Overloading – when a class has two or more methods with the same name
the methods must differ in number or type of parameters
the return type alone cannot be used to distinguish two methods
Examples
A class typically has several constructors that differ in number or type of params
The methods breed() and breed(Location loc) in the class Flower
Method Overloading
Overriding – when a derived class changes/overrides the implementation of a method inherited from a base class
the method signature must remain identical for each class down the inheritance hierarchy
(identical return type, number and type of parameters, public/private access)
Examples
The methods speak() and getHumanAge(int year) are implementeddifferently in the class Cat and its parent class Pet
The method act() is implemented differently by every Actor in the GridWorld hierarchy
Method Overriding