Inheritance, abstract classes and interfaces

Similar documents
Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Java Programming Language

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

Chapter 13 - Inheritance

Java Interview Questions and Answers

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Programming Languages Featherweight Java David Walker

History OOP languages Year Language 1967 Simula Smalltalk

Inheritance, overloading and overriding

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Object-Oriented Programming Lecture 2: Classes and Objects

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

CS 111 Classes I 1. Software Organization View to this point:

Java (12 Weeks) Introduction to Java Programming Language

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

CS193j, Stanford Handout #10 OOP 3

Construction of classes with classes

Object-Oriented Programming: Polymorphism

AP Computer Science Java Subset

Part I. Multiple Choice Questions (2 points each):

D06 PROGRAMMING with JAVA

LAB4 Making Classes and Objects

Polymorphism. Why use polymorphism Upcast revisited (and downcast) Static and dynamic type Dynamic binding. Polymorphism.

Description of Class Mutation Mutation Operators for Java

Teach Yourself Java in 21 Minutes

CS-XXX: Graduate Programming Languages. Lecture 25 Multiple Inheritance and Interfaces. Dan Grossman 2012

Programmation 2. Introduction à la programmation Java

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

ICOM 4015: Advanced Programming

Java Application Developer Certificate Program Competencies

An Introduction To UML Class Diagrams Classes

Part 3: GridWorld Classes and Interfaces

The Interface Concept

Object-Oriented Programming in Java

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Fundamentals of Java Programming

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Object Oriented Software Design

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Java CPD (I) Frans Coenen Department of Computer Science

Tutorial on Writing Modular Programs in Scala

Abstract Class & Java Interface

Inheritance in Programming Languages

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

Introduction: Abstract Data Types and Java Review

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

What is Java? Applications and Applets: Result of Sun s efforts to remedy bad software engineering practices

Software Engineering Techniques

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

java Features Version April 19, 2013 by Thorsten Kracht

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Advanced Data Structures

Introducing Variance into the Java Programming Language DRAFT

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Twin A Design Pattern for Modeling Multiple Inheritance

Génie Logiciel et Gestion de Projets. Object-Oriented Programming An introduction to Java

Block IQ. Marko Boon Jacques Resing

Unit Testing and JUnit

Chapter 1 Java Program Design and Development

J a v a Quiz (Unit 3, Test 0 Practice)

Compile-time type versus run-time type. Consider the parameter to this function:

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Object-Oriented Programming

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

Computing Concepts with Java Essentials

Génie Logiciel et Gestion de Projets. Object-Oriented Programming An introduction to Java

Computer Science K-12

A Comparison of the Object-Oriented Features of Ada 95 and Java

Chapter 1 Fundamentals of Java Programming

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Using Inheritance and Polymorphism

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

Introduction to Object-Oriented Programming

Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages. Corky Cartwright Swarat Chaudhuri November 30, 20111

CSE 1020 Introduction to Computer Science I A sample nal exam

DIPLOMADO DE JAVA - OCA

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

Mouse Event Handling (cont.)

Grundlæggende Programmering IT-C, Forår Written exam in Introductory Programming

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

14/05/2013 Ed Merks EDL V1.0 1

2 The first program: Little Crab

Abstract. a

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

JavaScript. JavaScript: fundamentals, concepts, object model. Document Object Model. The Web Page. The window object (1/2) The document object

Automatic generation of fully-executable code from the Domain tier of UML diagrams

Android Application Development Course Program

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Crash Course in Java

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

iphone SDK Enrolled students will be invited to developer program Login to Program Portal Request a Certificate Download and install the SDK

Abstract Classes. Suppose we want write a program that manipulates various types of bank accounts. An Account typically has following features;

Transcription:

Inheritance, abstract classes and interfaces Inheritance R. Grin Java: inheritance and polymorphism page 2 Reusability If you get a compiled A.class you can use it: A a = new A(); int y = a.compute(x); But, sometimes, you would like to modify slightly the behavior of the instances of A It is not possible if you have not got the source code A.java Inheritance Withinheritance you can create an object whose behavior is slightly different from an instance of the A class: an instance of a subclass of A, with n new methods n modified A methods R. Grin Java: inheritance and polymorphism page 3 R. Grin Java: inheritance and polymorphism page 4 Inheritance in Java Inheritance in Java Each class has one and only one superclass: no multiple inheritance The class inherits the members of its superclass It is possible to n add new methods n modify some methods of its superclass But it is not possible to remove methods of the superclass The keyword extends indicates the superclass of a class: class Subclass extends Superclass { By default, a class inherits from the classobject R. Grin Java: inheritance and polymorphism page 5 R. Grin Java: inheritance and polymorphism page 6 1

Example superclass public class Rectangle { private int x, y; // upper left point private int width, height; // Constructors // Methods getx(), setx(int), // getwidth(), getheight(), // contains(point), intersects(rectangle), // translate(int, int), tostring() public void draw(graphics g) { g.drawrect(x, y, width, height); R. Grin Java: inheritance and polymorphism page 7 Example - subclass public class ColoredRectangle extends Rectangle { private Color color; // new variable // Constructors // New methods public getcolor() { return this.color; public setcolor(color c) { this.color = c; // Overrided methods public void draw(graphics g) { g.setcolor(color); g.fillrect(getx(), gety(), getwidth(), getheight()); R. Grin Java: inheritance and polymorphism page 8 Examples Superclass Vehicle and subclasses Bicycle, Car and Truck Bicycle inherits fromvehicle and have several subclasses: MontainBike, RacingBike, Employe inherits from Person Image is the superclass of GifImage et JpegImage Bad use of inheritance Use inheritance to represent the relation is-a between classes Don t use inheritance just to reuse code For example, don t do that: ParallelepipedicRectangle inherits from Rectangle and adds a depth variable R. Grin Java: inheritance and polymorphism page 9 R. Grin Java: inheritance and polymorphism page 10 Overriding and Overloading Overriding is not the same as overloading : n you override a method when a method in a subclass has exactly the same signature as an inherited method Overriding methods n you overload a method when another method has the same name but a different signature R. Grin Java: inheritance and polymorphism page 11 R. Grin Java: inheritance and polymorphism page 12 2

The super keyword Constraints about redefinitions (1) In a method, the super keyword can be used to manipulate a method of the superclass, overridden (or not) in the current class: int m(int i) { return 500 + super.m(i); In Java, the return type must be exactly the same as the return type of the overridden method R. Grin Java: inheritance and polymorphism page 13 R. Grin Java: inheritance and polymorphism page 14 Constraints about redefinitions (2) Visibility keywords : the overriding method cannot be less accessible than the overridden method (for exampleit is not possible to declareprivate a method that overrides a public method) Exceptions: the overriding method cannot declare throwing more exceptions than the overridden method declares (subclasses are allowed) Constructor Chaining R. Grin Java: inheritance and polymorphism page 15 R. Grin Java: inheritance and polymorphism page 16 First instruction of a constructor The first instruction of a constructor is a call to n a constructor of the superclass: super(...) n another constructor of the current class: this(...) Otherwise, the compiler adds an implicit call to the constructor without parameter of the superclass the first instruction, explicit or implicit, is a call to a constructor of the mother class R. Grin Java: inheritance and polymorphism page 17 Superclass public class Rectangle { private int x, y, weight, height; public Rectangle(int x, int y, int weight, int height) { this.x = x; this.y = y; this.weight = weight; this.height = height; R. Grin Java: inheritance and polymorphism page 18 3

Constructors of the subclass public class ColoredRectangle extends Rectangle { private Color couleur; public ColoredRectangle(int x, int y, int weight, int height, Color color) { super(x, y, weight, height); this.color = color; public ColoredRectangle(int x, int y, int weight, int height) { this(x, y, weight, height, Color.black); R. Grin Java: inheritance and polymorphism page 19 Implicit call of the constructor without parameter of the superclass If the first instruction of a constructor is neither super() nor this(), the compiler adds an implicit call to the constructor without parameters of the superclass A constructor of the superclass is always executed before the other instructions of the constructor R. Grin Java: inheritance and polymorphism page 20 The really first instruction executed by a constructor But the first instruction executed by the constructor of the superclass is the call to a constructor of the superclass of the superclass So, the really first instruction executed by a constructor is the constructor of the class Object Protected access R. Grin Java: inheritance and polymorphism page 21 R. Grin Java: inheritance and polymorphism page 22 What is inherited? If B extends A, it inherits of all the members of A (but not the constructors) But, B cannot access private members of the A class; these members will be implicitly used by B, but B will not be able to name or to manipulate them Access to protected members If a class declares protected one of its member (or constructor), this member will be accessible by its subclasses protected gives also access to the member to all the classes of the same package Precision: if the subclass is not in the same package, instances of the subclass will not have access to the protected members for the instances of the superclass R. Grin Java: inheritance and polymorphism page 23 R. Grin Java: inheritance and polymorphism page 24 4

Example class A { protected int m() { class B extends A { public int m2() { int i = m(); // always allowed A a = new A(); i += a.m(); // not always allowed when is it allowed? R. Grin Java: inheritance and polymorphism page 25 Object class R. Grin Java: inheritance and polymorphism page 26 Object class java.lang.object is the root of the inheritance hierarchy: the superclass of all the classes Object class has no instance or class variable All the methods of the Object class are inherited by all the classes The more often used methods of Object are: ntostring() nequals() tostring method public String tostring() returns a description of the instance Very useful for debugging Must be overridden by almost all the classes R. Grin Java: inheritance and polymorphism page 27 R. Grin Java: inheritance and polymorphism page 28 equals method public boolean equals(object object) returns true if object is equal to this, the current instance, according to an equality relation Example: 2 instances of Fraction are equal if f1.num x f2.den = f1.den x f2.num In the Object class, obj1.equals(obj2) obj1 == obj2 equals and hashcode methods Specification of Java: if 2 objects are equal, they must have the same hashcode So, if equals is overridden, hashcode must be overridden too It is not always easy to override the hashcode method R. Grin Java: inheritance and polymorphism page 29 R. Grin Java: inheritance and polymorphism page 30 5

Example of tostring and equals public class Fraction { private int num, den; public String tostring() { return num + "/" + den; public boolean equals(object o) { if (! (o instanceof Fraction)) return false; return num * ((Fraction)o).den == den * ((Fraction)o).num; a/b = c/d R. Grin Java: inheritance and polymorphism page 31 Example of hashcode public int hashcode() { /* Reduce the fraction */ Fraction f = reduce(); return (17 + f.num * 37) * 37 + f.den; a.d = b.c R. Grin Java: inheritance and polymorphism page 32 getclass() method public Class getclass() returns the class of the instance java.lang.class contains a getname() method which returns the qualified name of the class Polymorphism R. Grin Java: inheritance and polymorphism page 33 R. Grin Java: inheritance and polymorphism page 34 A question Suppose that B extends A and that the method m() of A is overridden in B Which method m() will be executed in the following code, the one of A or of B? A a = new B(5); a.m(); a is an object of class B but declared as an A The method that is called depends only on the real type (B) of a (not the declared type, herea). So, the method from B will be executed R. Grin Java: inheritance and polymorphism page 35 Polymorphism It is the fact that the same call to a method in the code, can be executed by different methods For instance, A a = x.f(); a.m(); f can return an instance of A or of any subclass of A the method that will be executed can be the method m() of A or of any subclass of A R. Grin Java: inheritance and polymorphism page 36 6

Example of polymorphism public class Figure { public void draw(graphics g) { public class Rectangle extends Figure { public void draw(graphics g) { public class Circle extends Figure { public void draw(graphics g) { Empty method Figure.java Rectangle.java Circle.java R. Grin Java: inheritance and polymorphism page 37 Example of polymorphism (cont.) public class Drawing { private Figure[] figures; public void draw(graphics g) { for (int i=0; I < figures.length; i++) { figures[i].draw(g); public static void main(string[] args) { Drawing drawing = new Drawing(30); drawing.add(new Circle(center, radius)); drawing.add(new Rectangle(p2, width, height)); drawing.draw(g); R. Grin Java: inheritance and polymorphism page 38 Static type checking and polymorphism When it encounters a.m() the compiler must be sure that the class of the object a contains a method m() For instance, because of figures[i].draw(g), it is necessary that the class Figure contains the method draw(graphics) Else you will get an compilation error Advantage of polymorphism A good use of polymorphism can avoid a program with a lot of tests (if, switch/case ): for (int i = 0; i < figures.length; i++) { if (figures[i] instanceof Rectangle) { // Draw a rectangle else if (figures[i] instanceof Circle { // Draw a circle R. Grin Java: inheritance and polymorphism page 39 R. Grin Java: inheritance and polymorphism page 40 Advantage of polymorphism With polymorphism you can easily extend an application For instance, if you add a new type of figure, you don t have to modify the code of the method draw of the Drawing class public void draw(graphics g) { for (int i=0; i < figures.length; i++) { figures[i].draw(g); Without polymorphism You will have to add code to draw the new type of figure: else if (figures[i] instanceof Rhomb) { // draw a rhomb R. Grin Java: inheritance and polymorphism page 41 R. Grin Java: inheritance and polymorphism page 42 7

Conclusion Polymorphism is a fundamental issue in Object Oriented Programming and the basis for an efficient use of inheritance Polymorphism is achieved by the late binding mechanism: the method that will be called is determined at run time, not at compilation time Cast R. Grin Java: inheritance and polymorphism page 43 R. Grin Java: inheritance and polymorphism page 44 Cast : conversion between classes UpCast: subclasses superclass To cast is to enforce the compiler to see an object with a certain type In Java, the only allowed casts between objects are between subclasses and superclasses An object is considered with the type of an ancestor class instead of its real type It is always possible to perform an upcast (relation is-a of inheritance) So, upcast can be implicit R. Grin Java: inheritance and polymorphism page 45 R. Grin Java: inheritance and polymorphism page 46 Example of upcast public class Engineer extends Employee { public class Project { public void add(employee employee) { // somewhere else Ingineer i1 = new Ingineer(2563, "John"); project.add(i1); DownCast: superclass subclass An object is considered of a type of a subclass of its declaration class A downcast is not always possible ; at runtime, the type of the object will be checked Downcast is used to call a method of the subclass that does not exist in the superclass A downcast must always be explicit R. Grin Java: inheritance and polymorphism page 47 R. Grin Java: inheritance and polymorphism page 48 8

Example of downcast // Figures are added in an ArrayList ArrayList figures = new ArrayList(); figures.add(new Circle(center, radius)); figures.add(new Rectangle(p1, p2)); // get(i) return an Object; a cast is // necessary to call the draw method ((Figure)figures.get(i)).draw(g); Keyword final final class: cannot have subclasses final method: cannot be overridden final variable: cannot be modified after initialization final parameter: cannot be modified in the method body R. Grin Java: inheritance and polymorphism page 49 R. Grin Java: inheritance and polymorphism page 50 Abstract classes and methods Abstract classes A method is abstract (modifier abstract) when you only give its signature and its return type, not its implementation A class must be declared abstract if it contains an abstract method Abstract classes are useful for classifying classes or for code factorization R. Grin Java: inheritance and polymorphism page 51 R. Grin Java: inheritance and polymorphism page 52 Example of an abstract class public abstract class Figure { public abstract void draw(graphics g); Interfaces R. Grin Java: inheritance and polymorphism page 53 R. Grin Java: inheritance and polymorphism page 54 9

Interfaces Example of interface An interface is a 100% abstract class, without any variables An interface can contain constants (static final) public interface Figure { public void draw(graphics g); Methods and constants are necessarily (and implicitly) public An interface can inherit (keyword extends) from several interfaces R. Grin Java: inheritance and polymorphism page 55 R. Grin Java: inheritance and polymorphism page 56 Examples of interfaces from the API public interface Comparable { int compareto(object o); public interface MouseListener extends EventListener { void mouseclicked(mouseevent e); void mouseentered(mouseevent e); void mouseexited(mouseevent e); void mousepressed(mouseevent e); void mousereleased MouseEvent e); Implementation of an interface A class can implement (keyword implements) one or several interfaces If C is a class that implements an interface, it must implement all the methods of the interface Otherwise C must be declared abstract R. Grin Java: inheritance and polymorphism page 57 R. Grin Java: inheritance and polymorphism page 58 Example of an implementation public class City implements Comparable { private String name; private int nbinhabitants; public int compareto(object object) { return nbinhabitants - (City)objet.nbInhabitants; Interfaces are types An interface can be used exactly everywhere you can use a class name An interface defines the services proposed by the class that implements it; It describes a behavior R. Grin Java: inheritance and polymorphism page 59 R. Grin Java: inheritance and polymorphism page 60 10

Polymorphism and interfaces Using interfaces For polymorphism, an interface plays the role of a superclass: the example of polymorphism works very well if the abstract class Figure is an interface You can apply polymorphism with classes from different inheritance hierarchies if they implement a same interface The advantage of interface is that a class can implement several interfaces R. Grin Java: inheritance and polymorphism page 61 R. Grin Java: inheritance and polymorphism page 62 Cast and interfaces We can cast (upcast and downcast) between a class and an interface it implements (and upcast between an interface and Object): // upcast City fi Comparable Comparable c1 = new City("Cannes", 200000); Comparable c2 = new City("Nice", 500000); if (c1.compareto(c2)) // upcast Comparable fi Object // downcast Comparable fi City System.out.println( (City )c2.getnbinhabitants()); Reuse R. Grin Java: inheritance and polymorphism page 63 R. Grin Java: inheritance and polymorphism page 64 How class C2 can reuse code of a class C1 Inherits from C1 Composition: an instance variable of the C2 is of type C1 Delegation: C2 delegates the execution of one of its methods to an instance of C1; this instance can be n an instance variable of C2 n created by the method of C2 to do the work Drawbacks with inheritance Static: if an object must play different roles at different moments, it is not possible to use inheritance For instance, if a person can be a pilot or a client of an airplane company, 3 classes Person, with 2 subclasses Client and Pilot are no use Poor encapsulation for the superclass: often difficult to change the superclass, especially if protected variables have been used Not possible to inherit from a final class (String for instance) R. Grin Java: inheritance and polymorphism page 65 R. Grin Java: inheritance and polymorphism page 66 11

Advantages of inheritance Conclusion Easy to use: basic mechanism of the language Allow polymorphism (but also possible with interface) Easy to understand if it represents a is-a relation Flexible because you can modify inherited behavior (by overriding methods) To reuse classes, n Use inheritance to represent static is-a relations n Use delegation and composition in the other cases R. Grin Java: inheritance and polymorphism page 67 R. Grin Java: inheritance and polymorphism page 68 12