Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
ICS 4U1 – Unit 2 Data Structures Name: _________________________ Inheritance Classes with Similar Design In your last set of exercises, you completed the game Black Jack. Consider the role of the Dealer and the Player: - both should have a hand of cards and a score - both should be able to receive cards, tally the score of their hand, modify their points, display their hand, and clear their hand - both should have a strategy for playing, but the Dealer must have an autoplay functionis controlled by the user whereas the Dealer is controlled by the program All of the behaviours and attributes of the classes are similar except for how they play the game. It seems redundant to create two separate classes that have so much in common. This is where the notion of inheritance comes from. We can base one class off of another, thereby inheriting the behaviour and member variables, and tailor certain methods to the needs of the class. Extending a Class For the design of Black Jack, the Player class was created first with all member variables and methods completed (by you!). Afterwards, the Dealer class was created with the following definition: class Dealer extends Player {…} This indicates to the compiler that Dealer is inheriting all of the public methods and member variables of the Dealer class. We call Player the superclass of Dealer, and Dealer is a subclass of Player. The constructor for Dealer has a new term: public Dealer() { super(); } super () is not a method we’ve seen before. This is actually a call to the constructor of the superclass. If the constructor of the Player class required parameters, we’d send them through the call to super(). ICS 4U1 – Unit 2 Data Structures Name: _________________________ Overriding Methods We do not have to re-type the methods for the Dealer class, but we can override them if necessary by typing a new definition in the subclass. For example, suppose we wanted the Dealer to receive double the points it should for each call to score(). By redefining the method in the Dealer class, the compiler knows to use the Dealer’s version of score() rather than calling upon the Player’s version. public void addPoints(int p) { this.score = score + 2*p; } At this point, if the a method is called on an object of type Dealer, the compiler first checks to see if the method exists in the Dealer class before checking for the method in the Player class. Protected Methods and Member Variables Subclasses inherit public instance methods and member variables, but not those that are private. In order to permit private instance methods and member variables to be inherited, use the protected modifier instance of private. Instance methods and member variables marked as protected will remain private to the sub and superclasses. Polymorphism One of the major benefits of using inheritance in your class design is in order to store a variety of data as a common type. For instance, suppose we create a class that represents an Animal. class Animal { // Member variables boolean isDomestic; String name; // Constructor public Animal(boolean d, String n) { this.isDomestic = d; this.name = n; } public void makeNoise() { System.out.println(“ring-ding-ding”); } } ICS 4U1 – Unit 2 Data Structures Name: _________________________ However, different Animals should have different makeNoise() methods. From here, we extend the Animal class to create subclasses Cat, Dog, and Hamster. Each subclass will have its own makeNoise() method defined. An example is shown below. class Dog extends Animal { // Member variables – inherits all of the member // variables from the Animal class. String breed; // Constructor public Dog(String n, String b) { // Dogs are domestic! this.isDomestic = true; // Set the name and breed accordingly this.name = n; this.breed = b; } // Overridden method public void makeNoise() { System.out.println(“woof!”); } } Polymorphism refers to the fact that Java sees all of the subclasses as valid instances of the superclass. This means that we can have an array of Animal objects which actually contain a mixture of Dog, Cat, and Hamster objects. The following code is valid: Animal[] pets = new Animal[10]; pets[0] = new Dog(“Lassie”, “Collie”); pets[1] = new Hamster(“Hammy”, “Long-haired”); pets[2] = new Cat(“Puss”, “Himalayan”); Problem: If we have an array of type Animal, how do we know whether or not each element in the array is a Dog, Cat or Hamster? After all, we’d want to be able to make use of the proper makeNoise() method if possible. Solution: Java is smart! If the Animal object in the array is really of type Dog, Java knows to call the makeNoise() method of the Dog class. ICS 4U1 – Unit 2 Data Structures Name: _________________________ We can also use the instanceof command to determine whether a given Animal is an instance of a Dog or not. Suppose mysteryAnimal is a variable of type Animal, but we don’t know if it’s a Dog, Cat, or Hamster. The following code detects whether or not mysteryAnimal is of type Dog. if (mysteryAnimal instanceof Dog) { System.out.println(“It’s a Dog!”); } Objects: The Root of All Inheritance Every class in Java is an Object. Although it’s not explicitly stated, even a class that seems to not extend anything actually extends the Java Object class. The Java Object class has two methods that we commonly override: public boolean equals(Object obj) // Indicates whether some other object is “equal” to this one public String toString() // Returns a string representation of this object. Note: The String class actually overrides the equals() method to do what we know it does – compare the equality of two String objects. In the case of the Dog class, we might say that two Dogs are equal if they have the same name with the same breed. A sample implementation for the Dog class is below: public boolean equals(Object obj) { // if the object is null, it’s definitely not equal to this Dog. if (obj == null) return false; // if the object is not a Dog, it’s also not equal to this Dog. if (!obj instanceof Dog) return false; // The other object is a Dog – let’s compare member vars. // First, we force Java to treat obj as a dog by using a cast. Dog otherDog = (Dog) obj; // Putting (Dog) before obj treats it as a Dog object. if (this.name.equals(otherDog.name) && this.breed.equals(otherDog.breed)) { return true; } return false; // Returns false otherwise. } ICS 4U1 – Unit 2 Data Structures Name: _________________________ The toString() method is useful for displaying the data held inside of an object. A sample implementation for the Dog class is below. public String toString() { return (“I’m a “ + this.breed + “ and my name is “ + this.name); } Inheritance - Assignment 1. The image below demonstrates a UML (Unified Modeling Language) diagram. UML diagrams are useful for showing the inheritance relationship between classes. An arrow is drawn from one class to another if it extends that class. Study the class hierarchy carefully and consider the questions that follow. Which of the statements are valid and which are not? Answer the questions in a document called Inheritance – Exercises. a) Vehicle v = new Car(); b) Truck t = new Truck(); c) Bus b = new MotorVehicle(); d) Object o = new Truck(); e) Car c = new Bus(); f) Bus b = new Vehicle(); g) MotorVehicle m = new LightTruck(); ICS 4U1 – Unit 2 Data Structures Name: _________________________ 2. Referring to the extended class diagram shown below, which of the following conversions would require a cast? a) Dog to Husky b) Mammal to Animal c) Dog to Animal d) Vertebrate to Beagle 3. Using the classes shown in Question 2 above, suppose we construct the following variables. Mammal pet = new Dog(); Dog toby = new Samoyed(); Dog sampson = new Dog(); Consider the following statements. For each one, state whether it is valid, incorrect but fixable with a cast, or not valid and not fixable with a cast. If a cast will make the statement valid, state the cast. (a) Samoyed s = pet; (b) Object o = sampson; (c) Samoyed s = toby; (d) Dog d = pet; (e) Mammal m = toby; (f) Samoyed s = sampson; ICS 4U1 – Unit 2 Data Structures Name: _________________________ 4. (Programming) You will need to develop a system that can track employee information for organizations. First, you must complete the Organization class using any member variables of your choosing. The Organization class must have these methods implemented (more, if you wish): public class Organization { // Constructor that receives the name and number of employees. public Organization(String n, int e) {} // Returns the number of employees belonging to this organization. public int getNumberOfEmployees() {} // Returns the name of the organization. public String getNameOfOrganization() {} // Returns true if this Organization object is equal to obj. public boolean equals(Object obj) {} // Returns a String representation of the Organization. public String toString() {} } You are provided with a class called Person. The class has member variables for the name, sex, and birthday of a person (see the Java API about the Date class). Do not change this class! Complete the Java class called Employee that extends Person. Your class may contain any member variables that you wish, but it must implement the following methods: // Constructor for the Employee class. // Receives the name, sex, birth date, job title, and Organization // for which the employee works. public Employee(String n, String s, Date d, String jt, Organization o) {} // Returns the employee’s job title. public String getJobTitle() {} // Returns the String representation of the Organization for which the // employee works. public String getOrganization() {} // Returns true if this Employee object is equal to obj. // Two employees are equal if they have the same name, sex, birthdate, job // title, and work for the same organization. public boolean equals(Object obj) {} // Returns a string representation of the employee that contains all of // their workplace attributes. public String toString() {}