1 / 48

Object-Oriented Programming

roll. sides. face. getSides. getFace. Object-Oriented Programming. 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:

ahmed-lott
Télécharger la présentation

Object-Oriented Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. roll sides face getSides getFace Object-Oriented Programming

  2. Object-Oriented Programming • Problem solving approach that focuses on describing the participating entities in the problem domain and the interactions between them.

  3. Object-Oriented Programming The four key concepts: classes and objects encapsulation inheritance polymorphism

  4. 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”

  5. roll sides face getSides getFace 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

  6. 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

  7. 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

  8. roll sides face getSides getFace 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

  9. data members (properties) methods (behavior) 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 } }

  10. 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 } }

  11. 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; } }

  12. 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; } }

  13. 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; } }

  14. 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; } }

  15. 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)

  16. 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);

  17. roll sides face getSides roll getFace sides face getSides getFace roll sides face getSides getFace Creating and Using Objects 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()); } }

  18. 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

  19. 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; } }

  20. roll sides face getSides roll getFace sides face getSides getFace roll sides face getSides getFace What Needs to Change? 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()); } }

  21. Inheritance

  22. 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)

  23. 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 do for a generic Pet!

  24. Inheritance Pet Cat Dog Hamster

  25. Same for all 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

  26. 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 to Cats/Dogs

  27. 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”); } }

  28. Inherit from Pet class Call parent (Pet) constructor Use my own methods inherited from parent (Pet) class Only Dogs can do this 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; } }

  29. Inherit from Pet class Call parent (Pet) constructor Use my own methods inherited from parent (Pet) class Only Cats 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; } }

  30. Inheritance 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 } }

  31. 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

  32. Polymorphism

  33. 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)

  34. Polymorphism 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 } }

  35. 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 } }

  36. 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); } }}

  37. 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): } }

  38. Abstract Classes and Methods

  39. 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.)

  40. 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(); }

  41. Abstract Classes and Methods 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 } }

  42. Static Data Members and Methods

  43. 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()

  44. Static Data Members and Methods 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 } }

  45. Method OverloadingvsMethod Overriding

  46. Method Overloading 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

  47. Method Overriding Overriding – when a derived class changes/overrides the implementationof a method inherited from a base class the method signature must remain identical for each class down the inheritancehierarchy (identical return type,number and type of parameters, public/private access) Examples The methods speak() and getHumanAge(int year) are implemented differently in the class Cat and its parent class Pet The method act() is implemented differently by every Actor in the GridWorld hierarchy

  48. The End (Part I)

More Related