Inheritance, polymorphism, interfaces

Similar documents
Inheritance E, xc Ex eptions ceptions I/O

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

First IS-A Relationship: Inheritance

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Inheritance, Polymorphism, and Interfaces

More Relationships Between Classes

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

CS 251 Intermediate Programming Inheritance

Java Object Oriented Design. CSC207 Fall 2014

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Inheritance and Polymorphism

CS-202 Introduction to Object Oriented Programming

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object-Oriented Programming

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Polymorphism. Object Orientated Programming in Java. Benjamin Kenwright

Example: Count of Points

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Java Magistère BFA

Inheritance & Polymorphism. Object-Oriented Programming

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

RemedialJava Packages, Collec4ons, Inheritance 7/09/17. (remedial) Java. Packages. Anastasia Bezerianos 1

Inheritance (continued) Inheritance

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

What is Inheritance?

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Announcements/Follow-ups

Exercise: Singleton 1

Introduction to Inheritance

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

Chapter 14 Abstract Classes and Interfaces

Inheritance and Polymorphism

COMP200 INTERFACES. OOP using Java, from slides by Shayan Javed

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

Inheritance. Transitivity

index.pdf January 21,

ITI Introduction to Computing II

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

ITI Introduction to Computing II

INHERITANCE. Spring 2019

Java Fundamentals (II)

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Example: Count of Points

Inheritance and Interfaces

Interface Class. Lecture 22. Based on Slides of Dr. Norazah Yusof

Upcasting. Taking an object reference and treating it as a reference to its base type is called upcasting.

Everything is an object. Almost, but all objects are of type Object!

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Chapter 5. Inheritance

Binghamton University. CS-140 Fall Chapter 9. Inheritance

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

AP CS Unit 6: Inheritance Notes

Instance Members and Static Members

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Inheritance (Outsource: )

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

Introduction to Object-Oriented Programming

Polymorphism. Arizona State University 1

Programming II (CS300)

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

CMSC 341. Nilanjan Banerjee

Java How to Program, 8/e

OVERRIDING. 7/11/2015 Budditha Hettige 82

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Rules and syntax for inheritance. The boring stuff

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

Programming 2. Inheritance & Polymorphism

type conversion polymorphism (intro only) Class class

26. Interfaces. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Programming II (CS300)

CST242 Object-Oriented Programming Page 1

Inheritance and Interfaces

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

25. Interfaces. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Practice for Chapter 11

Create a Java project named week10

Inheritance, and Polymorphism.

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

Polymorphism and Interfaces. CGS 3416 Spring 2018

CS313D: ADVANCED PROGRAMMING LANGUAGE

Object Orientated Programming Details COMP360

Making New instances of Classes

COMP 250 Fall inheritance Nov. 17, 2017

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

COMP 110/L Lecture 19. Kyle Dewey

Encapsulation. Inf1-OOP. Getters and Setters. Encapsulation Again. Inheritance Encapsulation and Inheritance. The Object Superclass

Inf1-OOP. Inheritance and Interfaces. Ewan Klein, Perdita Stevens. January 12, School of Informatics

CS111: PROGRAMMING LANGUAGE II

25. Generic Programming

ITI Introduction to Computing II

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

Transcription:

Inheritance, polymorphism, interfaces

"is-a" relationship Similar things (sharing same set of attributes / operations): a group / concept Similar groups (sharing a subset of attributes / operations): a bigger group / a more general concept A student is a person An employee is a person A manager is an employee An object of the subgroup "is-a" object of the supergroup

Inheritance Based on "is-a" relationship Subclass: more specialized; Superclass: more general Subclass is derived or inherits from superclass hence, the terms 'derived class' and 'base class' Objects of a subclass can be treated as objects of its superclass Objects in the same class have the same set of attributes (different values though) and operations Objects of subclass have all members of the superclass plus some more

java.lang.object The root of the class hierarchy. Every class has Object as a superclass. Provides a number of methods that are common to all objects (including arrays): clone() equals(object o) hashcode() finalize() tostring() + synchronization methods

Very basic inheritance Making a Game public class Dude { public String name; public int points = 100 public void sayname() { System.out.println(name); } } public void punchface(dude target) { target.points -= 10; }

Very basic inheritance Now create a Wizard... public class Wizard { // ugh, gotta copy and paste // Dude s stuff }

Very basic inheritance Now create a Wizard... But Wait! A Wizard does and has everything a Dude does and has!

Very basic inheritance Now create a Wizard... Don t Act Now! You don t have to Copy & Paste!

Buy Inheritance! public class Wizard extends Dude { } Wizard is a subclass of Dude Dude is a super-class of Wizard Wizard inherits Dude

Buy Inheritance! Wizard can use everything* the Dude has! wizard1.points += 1; Wizard can do everything* Dude can do! wizard1.punchface(dude1); You can use a Wizard like a Dude too! dude1.punchface(wizard1); *except for private fields and methods

Buy Inheritance! Now augment a Wizard public class Wizard extends Dude { String[] spells; public class cast(string spell) { // cool stuff here... points += 10; } }

Inheriting from inherited classes What about a Grand Wizard? public class GrandWizard extends Wizard { public void sayname() { System.out.println( Grand wizard + name) } } grandwizard1.name = Flash grandwizard1.sayname(); ((Dude)grandWizard1).sayName();

How does Java do that? What Java does when it sees grandwizard1.punchface(dude1) 1. Look for punchface()in the GrandWizard class 2. It s not there! Does GrandWizard have a parent? 3. Look for punchface()in Wizard class 4. It s not there! Does Wizard have a parent? 5. Look for punchface()in Dude class 6. Found it! Call punchface() 7. Decrease points from dude1

How does Java do that? What Java does when it sees ((Dude)grandWizard1).sayName() 1. Cast to Dude tells Java to start looking in Dude 2. Look for sayname()in Dude class 3. Found it! Call sayname()

What s going on?

You can only inherit from one class

You can only inherit from one class

You can only inherit from one class What if Thief and Elf both implement public void sneakup() If they implemented differently, which sneakup()does BadElf call? Java Doesn t Know!!

Chaining constructors Recall that when a class defines no constructor, the compiler will automatically add one. That is: class MaClasse { MaClasse() { super(); }... } super() - call the constructor of the superclass All constructors (except those of java.lang.object) call another constructor: a constructor of the superclass: super(...) another constructor of the same class: this(...) super() or this() are called on the first line of the new constructor

Virtual methods A subclass can redefine methods inherited from its superclass. to specialize these methods to suit the new problem New and old version must have the same prototype: same return type same argument types Private, final methods cannot be overriden Private members are hidden from subclass Objects of the subclass will work with the new version of the methods Superclass s methods of the same name can be reused by using the keyword super.methodname(...)

Polymorphism "exist in many forms" Object polymorphism: an object can be treated in different ways A Manager object can be seen as an Employee object as well Different objects interpret the same message differently: how do cats and dogs "talk"?

Upcasting Cast "up" the inheritance diagram Take an object reference and treat it as if it refers to its base type Cat c = new Cat("Tom"); Animal a = c; // upcasting Cannot invoke methods not provided by the base type a.chasetail(); //Error! method not found in class Animal But a.makeasound(); //"Meow ", Cat's makeasound() gets to run java.lang.classcastexception

Upcasting Cast "up" the inheritance diagram Take an object reference and treat it as if it refers to its base type Cat c = new Cat("Tom"); Animal a = c; // upcasting Cannot invoke methods not provided by the base type a.chasetail(); //Error! method not found in class Animal But a.makeasound(); //"Meow ", Cat's makeasound() gets to run java.lang.classcastexception

Upcasting Cast "up" the inheritance diagram Take an object reference and treat it as if it refers to its base type Cat c = new Cat("Tom"); Animal a = c; // upcasting Cannot invoke methods not provided by the base type a.chasetail(); //Error! method not found in class Animal But a.makeasound(); //"Meow ", Cat's makeasound() gets to run java.lang.classcastexception

Downcasting Cast "down" the inheritance diagram Animal animal = new Cat("Tom"); //upcast... Cat c = (Cat) animal; // downcast c.sayhello(); // "Meow.." But, not always possible. Why? Animal animal = new Animal("Dummy");... Cat c = (Cat) animal; // run-time error

Polymorphism Animal pet1 = new Cat("tom"); Animal pet2 = new Cow("mini");... pet1.makeasound(); pet2.makeasound(); The same message is interpreted differently depending on the object's type: Dynamic binding

Dynamic binding Method binding: connect a method call to a method body Static/early binding: performed by compiler/linker before the program is run. the only option of procedural languages. Dynamic/late binding: performed at run-time Java uses late binding, except for static, final, and private methods. private methods are implicitly final.

Abstract class Sometimes we don't want objects of a base class to be created Examples: Animal, Cat, Cow, Dog, An Animal object makes no sense What sort of sound does it make? Shape, Point, Rectangle, Triangle, Circle What does a generic Shape look like? How to draw it? Solution: make it an abstract class

Abstract class

Abstract method Sometimes we want a method in base class to serve as the common interface of subclasses' versions only: i.e. it should never be called Animal.makeASound(). It contains only dummy code Solution: make it an abstract method An abstract method has only a declaration and no method body (i.e. no definition): abstract void f(); The class containing an abstract method MUST be qualified as abstract An abstract method must be overriden and defined in a derived class so that objects of that class can be created (concrete class)

Abstract method

Generic programming Write code that can be reused for objects of many different types Indicate some type parameters instead of actual types Java 1.5: generic classes and methods

Generic classes General form of a generic class: class A<T1, T2,...> {...} T1, T2,... genericity parameters Example: class Stack<T>{ //generic stack private int s; private Object[] P = new Object[100]; public Stack() {s=-1;} public void push(t e) {s++; P[s]=e};... } Student tot = new Student("toto",...); Stack<Student> sstu = new Stack<Student>(); sstu.push(toto);

Generic methods public <T> void inspect(t t) { System.out.println("T: " + t.getclass().getname()); }... <String>inspect(String s);

Interfaces Manipulate objects, without knowing how they work Useful when you have similar but not identical objects Useful when you want to use code written by others Java does not support multiple inheritance What if we want an object to be multiple things?

Interfaces Define a contract that some classes will respect: Set of classes that share methods Declare an interface with the common methods Can use the interface, without knowing an object s specific type A special type of class which: Defines a set of method prototypes Does not provide the implementation for the prototypes, only the definition (signature) Can also define final constants A class can implement any number of interfaces

Interface example public interface Comparable<T>{ public int compareto(t o); } public class Name implements Comparable<Name>{... public int compareto(name n){... //implementation of compareto } }

Implementing interfaces Implementations provide complete methods:

Using interfaces All methods must be implemented All fields are final (cannot be changed) An interface name can be used as a class name: I i; //I interface If an class A implements an interface I, the subclasses of A automatically implement I also