More on Classes Inheritance and Polymorphism

Slides:



Advertisements
Similar presentations
Chapter 13 Abstraction and inheritance. This chapter discusses n Implementing abstraction. u extension u inheritance n Polymorphism/dynamic binding. n.
Advertisements

Final and Abstract Classes
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
1 Inheritance and Polymorphism. 2 This section is not required material!!!!  A note about inheritance… It’s not normally covered in 101 It will be gone.
Inheritance Inheritance Reserved word protected Reserved word super
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
1 Understanding Inheritance COSC 156 C++ Programming Lecture 8.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
What is inheritance? It is the ability to create a new class from an existing class.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
CSC 205 Java Programming II Polymorphism. Topics Polymorphism The principle of substitution Dynamic binding Object type casting Abstract class The canonical.
Inheritance in the Java programming language J. W. Rider.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Topic 4 Inheritance.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 11 Inheritance and Polymorphism.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Inheritance and Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
BY:- TOPS Technologies
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
 The word static is used to declare either a ________ variable or method.  Why do we use statics?  What is Polymorphism? class In general, we use a.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Inheritance and Polymorphism
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Lecture 12 Inheritance.
Inheritance and Polymorphism
Inheritance in Java.
Inheritance and Polymorphism
Object-Oriented Programming: Polymorphism
Object Oriented Programming
Designing for Inheritance
Understanding Inheritance
Week 6 Object-Oriented Programming (2): Polymorphism
Two big words Inheritance Polymorphism
Java – Inheritance.
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually.
Programming in C# CHAPTER 5 & 6
Computer Science II for Majors
Presentation transcript:

More on Classes Inheritance and Polymorphism Section 7/8

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

Musical instrument hierarchy Instruments Aerophones Reeded 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. Clarinets Saxophones Bassoons

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 Life-form Is-a Mammal Is-a Human Is-a Girl

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 Superclass Is-a Subclass

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

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 }

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.

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.

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

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.

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

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.

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.

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.

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.

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.

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.

Use of super Examples to come later 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

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

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

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

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

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: - that is, no object can be created from an abstract class - thus an abstract class can extend another abstract class, but further, a concrete class can extend an abstract class.

Why abstract class? - better to declare an abstract method: 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 - better to declare an abstract method: public abstract void bankCharge( );

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 } Note, abstract classes can have instance variables and some concrete methods, however they cannot be instantiated.

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. AC CC BankAccount ChequeAccount SavingsAccount PersonalAcct BusinessAcct HighInterestAcct ChildAcct

Example: Data Model Classes Shape Rectangle Circle Triangle The Shape class is abstract, whereas the other classes are concrete. All shapes have a position, a size, and a color. Specific shapes have different ways to be drawn.

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.