The Islamic University of Gaza Java II Lab ةزغ-تيملاسلإا تعماجلا...

13
The Islamic University of Gaza Java II Lab ميتسمعت الجا ا- غزةComputer Engineering Department Lab#4 لحاسوبم هندست ا قسEng.Abdalghani H Abujabal Inheritance & Polymorphism وجبلد الغني أب م.عبPage 1 Inheritance & Polymorphism Plan your programs with the future in mind. If there were a way to write java code such that you could take more vacations, how much would it be worth to you? What if you could write code that someone else could extend, easily? And if you could write code that was flexible, for those pesky last-minute spec changes, would that be something you are interested in? Inheritance Object-oriented programming allows you to derive new classes from existing classes. This is called inheritance. Inheritance is an important and powerful concept in Java. In fact, every class you define in Java is inherited from an existing class, either explicitly or implicitly. The classes you created in the preceding chapters were all extended implicitly from the java.lang.Object class. Superclass & Subclass: I looked at what all three classes have in common. They are all Shapes, and they all rotate and playSound. So I abstracted out the common features and put them into a new class called Shape. Then I linked the other three shape classes to the new Shape class, in a relationship called inheritance Square rotate() playSound() Circle rotate() playSound() Triangle rotate() playSound() Shape rotate() playSound() Shape rotate() playSound() Square Circle Triangle Superclass Subclasses

Transcript of The Islamic University of Gaza Java II Lab ةزغ-تيملاسلإا تعماجلا...

  • The Islamic University of Gaza Java II Lab غزة-الجامعت اإلسالميت Computer Engineering Department Lab#4 قسم هندست الحاسوب Eng.Abdalghani H Abujabal Inheritance & Polymorphism م.عبد الغني أبوجبل

    Page 1

    Inheritance & Polymorphism

    Plan your programs with the future in mind. If there were a way to write java code such that you could take more

    vacations, how much would it be worth to you? What if you could write code that someone else could extend, easily?

    And if you could write code that was flexible, for those pesky last-minute spec changes, would that be something you

    are interested in?

    Inheritance

    Object-oriented programming allows you to derive new classes from existing classes. This is called inheritance.

    Inheritance is an important and powerful concept in Java. In fact, every class you define in Java is inherited from an

    existing class, either explicitly or implicitly. The classes you created in the preceding chapters were all extended implicitly

    from the java.lang.Object class.

    Superclass & Subclass:

    I looked at what all three classes have in common.

    They are all Shapes, and they all rotate and playSound. So I abstracted out the common features and put them

    into a new class called Shape.

    Then I linked the other three shape classes to the new Shape class, in a relationship called inheritance

    Square

    rotate() playSound()

    Circle

    rotate() playSound()

    Triangle

    rotate() playSound()

    Shape

    rotate() playSound()

    Shape

    rotate() playSound()

    Square

    Circle

    Triangle

    Superclass

    Subclasses

  • The Islamic University of Gaza Java II Lab غزة-الجامعت اإلسالميت Computer Engineering Department Lab#4 قسم هندست الحاسوب Eng.Abdalghani H Abujabal Inheritance & Polymorphism م.عبد الغني أبوجبل

    Page 2

    You can read this as, “ Square inherits from Shape”, “Circle inherits from shape”, and so on. I removed rotate()

    and playSound() from the other shapes, so now there is only one copy to maintain.

    The Shape Class is called the superclass of the other three classes. The other three are the subclasses of the

    Shape. the subclasses inherit the methods of the superclass. In other words, if the Shape class has the

    functionality, then the subclasses automatically get the same functionality.

    I made the Triangle class override the rotate() and playSound() methods of the superclass Shape. Overriding just

    means that a subclass redefines one of its inherited methods when it needs to change or extend the behavior of

    that method.

    Understanding Inheritance

    When you design with inheritance, you put common code in a class and then tell other more specific classes that the

    common (more abstract) class is their superclass. when one class inherits from another, the subclass inherits from the

    superclass.

    In java, we say that the subclass extends the superclass. an inheritance relationship means that the subclass inherits the

    members of the superclass. when we say “members of a class” we mean the instance variables and methods.

    Note: public members are inherited, while private members are not.

    For example, if PantherMan is a subclass of SuperHero, the PantherMan class automatically inherits the instance

    variables and methods including suit, tights, specialPower, useSpecialPower() and so on. But the PantherMan subclass

    can add new methods and instance variables of its own, and it can override the methods it inherits from superclass

    SuperHero.

    Shape

    rotate() playSound()

    Square

    Circle

    Triangle

    rotate() //Triangle-//specific //rotate code playSound() //Triangle-//specific //playSound //code

    Superclass (more abstract)

    Subclasses(more specific)

    Overriding Methods

  • The Islamic University of Gaza Java II Lab غزة-الجامعت اإلسالميت Computer Engineering Department Lab#4 قسم هندست الحاسوب Eng.Abdalghani H Abujabal Inheritance & Polymorphism م.عبد الغني أبوجبل

    Page 3

    FriedEggMan does not need any behavior that’s unique, so he does not override any methods. The methods and

    instance variables in SuperHero are sufficient.

    PantherMan, though, has specific requirements for his suit and special powers, so useSpecialPower() and putOnSuit are

    both overridden in PantherMan class.

    Instance variables are not overridden because they do not need to be. They do not define any special behavior, so a

    subclass can give an inherited instance variable any value it chooses. PantherMan can set his inherited tights to purple,

    while FriedEggMan set his to white.

    SuperHero

    suit tights specialPower useSpecialPower() putOnSuit()

    PantherMan

    useSpecialPower() putOnSuit()

    FriedEggMan

    Instance variables (state,attributes)

    Methods (behavior)

    Superclass (more abstract)

    subclasses (more specific)

    Overriding methods

  • The Islamic University of Gaza Java II Lab غزة-الجامعت اإلسالميت Computer Engineering Department Lab#4 قسم هندست الحاسوب Eng.Abdalghani H Abujabal Inheritance & Polymorphism م.عبد الغني أبوجبل

    Page 4

    An inheritance example:

    Let’s design the inheritance tree for an animal simulation program.

    Imagine you are asked to design a simulation program that lets the user throw a bunch of different animals into an

    environment to see what happens. We do not have to code the thing now, we are mostly interested in the design.

    We have been given a list of some of the animals that will be in the program (Lion, Hippo, Tiger, Dog, Cat, Wolf). We

    know that each animal will be represented by an object, and that the objects will move around in the environment,

    doing whatever it is that each particular type is programmed to do.

    And we want other programmers to be able to add new kinds of animals to the program at any time.

    Look for objects that have common attributes and behaviors.

    We have to figure out the common, abstract characteristics that all animals have, and build those characteristics

    into a class that all animals classes can extend.

    Design a class that represents the common state and behavior.

    These objects are all animals, so we will make a common superclass called Animal. We will put in methods and

    instance variables that all animals might need.

    public class Doctor {

    boolean treatPatient;

    void treatPatient() { //perform a checkup

    } }

    public class FamilyDoctor extends Doctor {

    boolean makesHouseCalls;

    void giveAdvice() { //perform homespun advice

    } }

    public class Surgeon extends Doctor {

    void treatPatient() { //perform a checkup

    } void makeIncision() { // make incision }

    }

  • The Islamic University of Gaza Java II Lab غزة-الجامعت اإلسالميت Computer Engineering Department Lab#4 قسم هندست الحاسوب Eng.Abdalghani H Abujabal Inheritance & Polymorphism م.عبد الغني أبوجبل

    Page 5

    Decide if a subclass needs behaviors (method implementations) that are specific to that particular subclass type.

    You can notice that every animal has his own behavior of eating and making noise. So eat() and makeNoise()

    methods will be overridden for each subclass,

    Look for more opportunities to use abstraction, by finding two or more subclasses that might need common

    behavior.

    Animal

    picture food hunger makeNoise() eat() sleep() roam()

    Lion

    Hippo Dog

    Cat

    Wolf

    Tiger

  • The Islamic University of Gaza Java II Lab غزة-الجامعت اإلسالميت Computer Engineering Department Lab#4 قسم هندست الحاسوب Eng.Abdalghani H Abujabal Inheritance & Polymorphism م.عبد الغني أبوجبل

    Page 6

    Take a deep look to our design you can notice that Wolf and Dog might have some behavior in common, and

    the same thing goes for Lion, Tiger and Cat (According to biological organization).

  • The Islamic University of Gaza Java II Lab غزة-الجامعت اإلسالميت Computer Engineering Department Lab#4 قسم هندست الحاسوب Eng.Abdalghani H Abujabal Inheritance & Polymorphism م.عبد الغني أبوجبل

    Page 7

    Which method is called?

    The Wolf class had four methods. One inherited from Animal, one inherited from Canine, and two overridden in the

    Wolf class. When you create a Wolf object and assign it to a variable, you can use the dot operator on the reference

    variable to invoke all four methods. But which version of those methods gets called?!

    When you call a method on an object reference, you are calling the most specific version of the method for that object

    type.

    In other words, the lowest one wins

    Using IS-A

    Remember that when one class inherits from another, we say that the subclass extends the superclass. When you want

    to know if one thing should extend another, apply the IS-A test.

    Triangle IS-A shape, Cat IS-A Feline, Surgeon IS-A Doctor

    Keep in mind that the inheritance IS-S relationship works in only one direction, Triangle IS-A Shape makes sense, so

    you can have Triangle extend Shape. But the reverse- Shape IS-S Triangle does not make sense, so Shape should not

    extend Triangle.

  • The Islamic University of Gaza Java II Lab غزة-الجامعت اإلسالميت Computer Engineering Department Lab#4 قسم هندست الحاسوب Eng.Abdalghani H Abujabal Inheritance & Polymorphism م.عبد الغني أبوجبل

    Page 8

    Polymorphism

    To see how polymorphism works, we have to step back and look at the way normally declare a reference and create an

    object.

    The important point is that the reference type AND the object type are the same. In this example, both are Dog.

  • The Islamic University of Gaza Java II Lab غزة-الجامعت اإلسالميت Computer Engineering Department Lab#4 قسم هندست الحاسوب Eng.Abdalghani H Abujabal Inheritance & Polymorphism م.عبد الغني أبوجبل

    Page 9

    But with polymorphism, the reference and the object can be different.

    Animal myDog = new Dog();

    With polymorphism, the reference type can be a superclass of the actual object type.

    When you declare a reference variable, any object that passes the IS-A test for the declared type of the reference

    variable cab be assigned to that reference. In other words, anything that extends the declared reference variable type

    cab be assigned to the reference variable. This lets you do things like make polymorphic arrays.

  • The Islamic University of Gaza Java II Lab غزة-الجامعت اإلسالميت Computer Engineering Department Lab#4 قسم هندست الحاسوب Eng.Abdalghani H Abujabal Inheritance & Polymorphism م.عبد الغني أبوجبل

    Page 10

    Also, You can have polymorphic arguments and return types.

    If you can declare a reference variable of a supertype, say, Animal, and assign a subclass object to it, say, Dog, think of

    how that might work when the reference is an argument to a method…

    class Vet {

    public void giveShot(Animal a) {

    //do horrible things to the Animal

    }

    }

    class PetOwner {

    public void start() { Vet v = new Vet(); Dog d = new Dog(); Hippo h = new Hippo*(; v.giveShot(d); v.giveShot(h); }

    }

  • The Islamic University of Gaza Java II Lab غزة-الجامعت اإلسالميت Computer Engineering Department Lab#4 قسم هندست الحاسوب Eng.Abdalghani H Abujabal Inheritance & Polymorphism م.عبد الغني أبوجبل

    Page 11

    Overriding vs. Overloading

    Overriding rules:

    1. Arguments must be the same, and return type must be compatible.

    Whenever the superclass takes as an argument, the subclass overriding the method must use that same

    argument. And whatever the superclass declares as a return type, the overriding method must declare either

    the same type or a subclass.

    2. The method cannot be less accessible.

    That means the access level must be the same. You cannot override a public method and make it private.

  • The Islamic University of Gaza Java II Lab غزة-الجامعت اإلسالميت Computer Engineering Department Lab#4 قسم هندست الحاسوب Eng.Abdalghani H Abujabal Inheritance & Polymorphism م.عبد الغني أبوجبل

    Page 12

    Overloading rules:

    1. The return types can be different.

    You are free to change the return types in overloaded methods, as long as the arguments lists are different.

    2. You cannot change ONLY the return type.

    If only the return type is different, it’s not a valid overload-the compiler will assume you are trying to override

    the method. And even that will not be legal unless the return type is a subtype of the return type declared in the

    supertype. To overload a method, you must change the argument list.

    3. You can vary the access levels in any direction.

  • The Islamic University of Gaza Java II Lab غزة-الجامعت اإلسالميت Computer Engineering Department Lab#4 قسم هندست الحاسوب Eng.Abdalghani H Abujabal Inheritance & Polymorphism م.عبد الغني أبوجبل

    Page 13

    Ex:

    Homework

    (The Person, Student, Employee, Faculty, and Staff classes) Design a class named Person and its two subclasses named

    Student and Employee. Make Faculty and Staff subclasses of Employee. A person has a name, address, phone number,

    and email address. A student has a class status (freshman, sophomore, junior, or senior). Define the status as a constant.

    An employee has an office, salary, and date-hired. Define a class named MyDate that contains the fields year, month, and

    day. A faculty member has office hours and a rank. A staff member has a title. Override the toString method in each class

    to display the class name and the person's name.

    Draw the UML diagram for the classes. Implement the classes. Write a test program that creates a Person, Student, Employee, Faculty, and Staff, and invokes their toString() methods.