1 / 30

More on Classes Inheritance and Polymorphism

Learning objectives. Explore the role of inheritance in object-oriented design.Introduce polymorphism.Develop a series of classes demonstrating the power of the inheritance.Explore superclasses and subclasses in Java.Introduce abstract classes.. Inheritance. Organizes objects in a top-down fas

freira
Download Presentation

More on Classes Inheritance and Polymorphism

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. More on Classes Inheritance and Polymorphism

    2. Learning objectives Explore the role of inheritance in object-oriented design. Introduce polymorphism. Develop a series of classes demonstrating the power of the inheritance. Explore superclasses and subclasses in Java. Introduce abstract classes.

    3. Inheritance Organizes objects in a top-down fashion from most general to least general Inheritance defines an “is-a” relationship A mountain bike “is a” kind of bicycle A SUV “is a” kind of automobile A border collie “is a” kind of dog A laptop “is a” kind of computer The is-a relationship is used to help us understand or even establish a class relationship

    4. Musical instrument hierarchy Idiophones: Solid instruments that are intrinsically sonorous, e.g., bell and cymbal; Membranophones: Instruments with taut membranes, e.g., drum and kazoo; Aerophones: Instruments that enclose and free masses of air, e.g., clarinet and whistle; Chordophones: Instruments with stretched strings, e.g., lyre and violin; Electrophones: Instruments with oscillating electric circuits, e.g. synthesizer and electric piano.Idiophones: Solid instruments that are intrinsically sonorous, e.g., bell and cymbal; Membranophones: Instruments with taut membranes, e.g., drum and kazoo; Aerophones: Instruments that enclose and free masses of air, e.g., clarinet and whistle; Chordophones: Instruments with stretched strings, e.g., lyre and violin; Electrophones: Instruments with oscillating electric circuits, e.g. synthesizer and electric piano.

    5. Musical instrument hierarchy The hierarchy helps us understand the relationships and similarities of musical instruments A clarinet “is a” kind of reeded instrument The “is-a” relationship is transitive A clarinet “is a” kind of lip reeded instrument A reeded instrument “is a” kind of aerophone A clarinet “is a” kind of aerophone

    6. Object-oriented terminology In object-oriented programming languages, a class created by extending another class is called a subclass. The class used for the basis is called the superclass Alternative terminology The superclass is also referred to as the base class The subclass is also referred to as the derived class

    7. Return to Inheritance Inheritance is means of organizing related classes The term inheritance refers to the fact that one class can inherit part or all of its structure and behaviour from another class. The class that does the inheriting is said to be a subclass of the class from which it inherits. If class B is a subclass of class A, we also say that class A is a superclass of class B. A subclass can add to the structure and behaviour that it inherits. It can also replace or modify inherited behaviour (though not inherited structure).

    8. What Is Inheritance? In Java, when you create a new class, you can declare that it is a subclass of an existing class. If you are defining a class named "B" and you want it to be a subclass of a class named "A", you would write class B extends A { . . // could include many additions to, and modifications of, // the code inherited from class A }

    9. Superclass and Subclass Several classes can be declared as subclasses of the same superclass. The subclasses (sibling classes) share some structures and behaviour they inherit from their common superclass. Structure is give by the type of the class, ex. if the superclass is a “life-form” then the subclasses are all going to have the same type, that is a life-form. Behaviour is determined by the actions of the life-form. You would expect this to be very different from a subclass inheriting behavior from the class musical instrument.

    10. Superclass and Subclass In the diagram, classes B, C, and D are sibling classes. Inheritance can also extend over several "generations" of classes. This is shown in the diagram, where class E is a subclass of class D which is itself a subclass of class A. In this case, class E is a subclass of class A, even though it is not a direct subclass.

    11. An example of inheritance Suppose that a program has to deal with motor vehicles, including cars, trucks, and motorcycles, etc. (This might be a program used by the DVLA to keep track of registrations.) The program could use a superclass named Vehicle to represent all types of vehicles. The Vehicle class could include: instance variables such as registrationNumber, owner and address instance methods such as transferOwnership() and changeAddress()

    12. An example of inheritance Three subclasses of Vehicle: Car, Truck, and Motorcycle -- could then be used to hold variables and methods specific to particular types of vehicles. The subclass Car might add instance variable and methods: The Car class might add instance variable numberOfDoors, the Truck class might add instance variable numberOfAxels, the Motorcycle class could add boolean instance variable hasSidecar.

    13. Class Vehicle The declarations of these classes in Java program would look, in outline, like this: class Vehicle { int registrationNumber; String owner; // instance variable owner void transferOwnership(String newOwner) { // instance method . . . } } class Car extends Vehicle { int numberOfDoors; // Instance variable . . . } class Truck extends Vehicle { int numberOfAxels; . . . } class Motorcycle extends Vehicle { boolean hasSidecar; . . . } // Note the use of extends in declaring each of the subclass

    14. Class Vehicle Note, Car is-a vehicle Truck is-a vehicle Motorcycle is-a vehicle ALL OK However, Vehicle is-a Car not true etc USE IS-A TEST TO ENSURE YOU HAVE THE CORRECT RELATIONSHIP.

    15. Class Vehicle Suppose that myCar is a variable of type Car that has been declared and initialised with the statement Car myCar = new Car(); myCar is an object of class Car As class Car extends class Vehicle, a Car also has all the structure and behaviour of a Vehicle.

    16. Class Vehicle Now myCar is-a Car and also is-a Vehicle, therefore the methods and instance variable of Vehicle are also available to Car. this means that myCar.registrationNumber, myCar.owner myCar.transferOwnership() also exist. The practical effect of this is that an object of type Car can be assigned to a variable of type Vehicle.

    17. Class Vehicle Thus, it would be legal to say Vehicle myVehicle = myCar; or even Vehicle myVehicle = new Car(); The object "remembers" that it is in fact a Car, and not just a Vehicle.

    18. Class Vehicle Information about the actual class of an object is stored as part of that object. It is even possible to test whether a given object belongs to a given class, using the instanceof operator. The test: if (myVehicle instanceof Car) ... determines whether the object referred to by myVehicle is in fact a Car. On the other hand, if myVehicle is a variable of type Vehicle the assignment statement myCar = myVehicle; would be illegal because myVehicle could potentially refer to other types of Vehicle that are not Car.

    19. Class Vehicle Thus, you are not allow to assign a value of type Vehicle to an object of type Car because not every vehicle is a Car. The solution here is to use type-casting. So, you could say: myCar = (Car)myVehicle; and you could even refer to ((Car)myVehicle).numberOfDoors.

    20. Use of super When we extend superclass to a new subclass we can make use of the constructors of the superclass by using the keyword super: super( ); invocation of superclass default constructor super(a, b); invocation of specific superclass constructor Examples to come later

    21. Overriding a method Overriding When a class is inherited the new class may need to provide a new version of a given method in the base class. When a sub-class method is identical in name and the number and type of arguments as a method in the class it is inheriting, it is said to override that method. public class A {   int i=0;   void doSomething() {i=5;} } class B extends A {   int j=0;   void doSomething(){     j=10;     i=15;   } } doSomthing in class B overrides doSomthing in class A

    22. Polymorphism A code expression can invoke different methods depending on the types of objects being manipulated Example: function overloading like method min() from java.lang.Math The method invoked depends on the types of the actual arguments Example int a, b, c; double x, y, z; … c = min(a, b); // invokes integer min() z = min(x, y); // invokes double min()

    23. Polymorphism Two types of polymorphism Syntactic polymorphism—Java can determine which method to invoke at compile time Efficient Easy to understand and analyze Pure polymorphism—the method to invoke can only be determined at execution time

    24. Abstract and Concrete Classes An abstract class defines data and methods common to all subclasses, but is never instantiated A concrete class inherits some data and methods, defines others, and is instantiated

    25. Abstract class An abstract class contains empty declaration as well as concrete definitions of methods and/or instance variables. An abstract class cannot be instantiated: The extension rules apply to an abstract class:

    26. Why abstract class? When an existing class is extended you may wish to force the programmer to redefine a method. example: public class BankAccount { public void bankCharge( ) { .............} } The method bankCharge could have a specific charge which is not appropriate in a subclass

    27. Abstract method An abstract method has no implementation - forces the implementers of subclasses to specify concrete implementations: public abstract class BankAccont { public abstract void bankCharge( ); ........... other methods }

    28. Inheriting abstract classes When you derive a class from an abstract class, you do not have to define all the abstract methods in the subclass. - then the subclass is also an abstract class. Therefore you cannot instantiated this class as objects. At some level you will have a class that contains no abstract methods. This will be a concrete class which can be used to define objects.

    29. Example: Data Model Classes

    30. Dynamic binding Suppose a class A has one or more subclasses. Then program code that apparently refers to objects of type A can be used to process objects belong to A’s subclasses. Java will wait until the code is executing before deciding which types of objects are being processed, and will then call the appropriate methods. This feature is called dynamic binding. For example, in the Book index example, both class Book and class Periodical extent class Item. Thus, when the statement it.display() is executed, Java will check the object referred to by it and will call the appropriate display method, depending on whether it refers to a Book or a Periodical.

More Related