Java Magistère BFA

Similar documents
Java Magistère BFA

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

Rules and syntax for inheritance. The boring stuff

INHERITANCE. Spring 2019

Java Fundamentals (II)

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Abstract Classes and Interfaces

Polymorphism. return a.doublevalue() + b.doublevalue();

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

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

What is Inheritance?

CMSC 132: Object-Oriented Programming II

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

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Java Magistère BFA

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

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

C12a: The Object Superclass and Selected Methods

More about inheritance

Inheritance (Part 5) Odds and ends

Introduction to Inheritance

The class Object. Lecture CS1122 Summer 2008

CLASS DESIGN. Objectives MODULE 4

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

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

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

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

Inheritance. The Java Platform Class Hierarchy

Object Oriented Programming. Java-Lecture 11 Polymorphism

Lecture 4: Extending Classes. Concept

Inheritance. Transitivity

COE318 Lecture Notes Week 8 (Oct 24, 2011)

Making New instances of Classes

Class, Variable, Constructor, Object, Method Questions

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Java Object Oriented Design. CSC207 Fall 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

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

CISC370: Inheritance

Binghamton University. CS-140 Fall Chapter 9. Inheritance

Inheritance and Polymorphism

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Chapter 5 Object-Oriented Programming

Super-Classes and sub-classes

COE318 Lecture Notes Week 9 (Week of Oct 29, 2012)

Check out Polymorphism from SVN. Object & Polymorphism

CS-202 Introduction to Object Oriented Programming

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

AP CS Unit 6: Inheritance Notes

Chapter 5. Inheritance

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

Practice for Chapter 11

Inheritance and Polymorphism

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Inheritance, polymorphism, interfaces

First IS-A Relationship: Inheritance

Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass

CS260 Intro to Java & Android 03.Java Language Basics

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

Inheritance (continued) Inheritance

More On inheritance. What you can do in subclass regarding methods:

CS 251 Intermediate Programming Inheritance

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

ITI Introduction to Computing II

C11: Garbage Collection and Constructors

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

C10: Garbage Collection and Constructors

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

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

ITI Introduction to Computing II

Topic 5 Polymorphism. " Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.

CO Java SE 8: Fundamentals

1.00 Lecture 13. Inheritance

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

Inheritance (Outsource: )

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

Programming II (CS300)

Informatik II (D-ITET) Tutorial 6

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

Java: introduction to object-oriented features

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Programming Exercise 14: Inheritance and Polymorphism

1- Differentiate between extends and implements keywords in java? 2- What is wrong with this code:

Week 5-1: ADT Design

Object-Oriented Concepts

Inheritance and Interfaces

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Object Model. Object Oriented Programming Spring 2015

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

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

Distributed Systems Recitation 1. Tamim Jabban

Transcription:

Java 101 - Magistère BFA Lesson 3: Object Oriented Programming in Java Stéphane Airiau Université Paris-Dauphine Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 1

Goal : Thou Shalt not re-code the same lines 1 public class Character { 2 public String name; 3 4 // default constructor 5 public Character(){ 6 nom = Unknown"; 7 } 8 9 public Character(String name){ 10 this.name = name; 11 } 12 } We want to create classes for representing Gauls et Romans with their specificities. How should we do this? Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 2

Goal : Thou Shalt not re-code the same lines 1 public class Character { 2 public String name; 3 4 // default constructor 5 public Character(){ 6 nom = Unknown"; 7 } 8 9 public Character(String name){ 10 this.name = name; 11 } 12 } We want to create classes for representing Gauls et Romans with their specificities. How should we do this? Copy-Paste the class Character, change the name with Roman or Gaul, and add the specific methods. Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 3

Goal : Thou Shalt not re-code the same lines 1 public class Character { 2 public String name; 3 4 // default constructor 5 public Character(){ 6 nom = Unknown"; 7 } 8 9 public Character(String name){ 10 this.name = name; 11 } 12 } We want to create classes for representing Gauls et Romans with their specificities. How should we do this? Copy-Paste the class Character, change the name with Roman or Gaul, and add the specific methods We do not want to duplicate code Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 4

Goal : Thou Shalt not re-code the same lines 1 public class Character { 2 public String name; 3 4 // default constructor 5 public Character(){ 6 nom = Unknown"; 7 } 8 9 public Character(String name){ 10 this.name = name; 11 } 12 } We want to create classes for representing Gauls et Romans with their specificities. How should we do this? Copy-Paste the class Character, change the name with Roman or Gaul, and add the specific methods We do not want to duplicate code Java one solution : inheritance. Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 5

Inheritance Inheritance : a class can be a subclass of another class. The parent/super class is more general the super class has all the properties of all the subclasses. subclasses have more specific properties. We obtain a class hierarchy. To express that a class is a subclass, we use the extends keyword in the class declaration. 1 class <subclass name> extends <superclass name> In Java, a sublass may extends only one superclass. Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 6

Example 1 public class Character { 2 private String name; 3 // Constructor 4 public Character(String name){ 5 this.name = name; 6 } 7 8 public String introduction(){ 0 return My name is + name; 10 } 11 } 1 public class Gaul extends Character { 2 2 3 public String intoduction(){ 4 What should I write? 5 } 6 7 8 public Gaul(String name){ 9 What should I write? 10 } 11 } Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 7

Consequences What happens to variables? What happens to methods? How to work with constructors Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 8

Protected members protected Methods or variable could be private or public public variables or methods are accessible to subclasses (of course!) private variables or methods remain inaccessible, even for subclasses! Careful however! Even though we do not have a direct access to those variables or methods, they do exist, but are simply hidden. protected : a class and its subclasses can access a protected method or variable. Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 9

Method overriding For public or protected method : either the behaviour is the same : we do not need to rewrite the method in the subclass or the behaviour is different : we need to re-write the method We can use an annotation @Override to note that we are redefining a method of a superclass. Java will check whether we actually override a method from the superclass. How to refer to the superclass? this : is a reference to the current class. super : is a reference to the superclass. Of course, we can add method in a superclass that do not exist in the superclass! Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 10

Example 1 public class Character { 2 private String name; 3 // Constructor 4 public Character(String name){ 5 this.name = name; 6 } 7 8 public String introduction(){ 9 return My name is + name; 10 } 11 } 1 public class Gaul extends Character { 2 3 @Override 4 public String introduction(){ 5 return super.introduction() + I am a Gaul ; 6 } 7 8 9 10 11 12 public static void main(string[] args){ 13 Gaul asterix = new Gaul( Astérix ); 14 System.out.println( asterix.introduction()); 15 } 15 } Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 11

Writing the constructor of a subclass The constructors name and signature follows the usual rules. For the body, there are two steps : 1 call the constructor of the superclass name : its name? super(<arguments list>) 2 write the code that is specific to the subclass. if you do not explicitly call the constructor of the superclass, Java will try to call the default constructor if it exists, everything goes fine if it does not exist compilation error! Solutions : either you add a call to a constructor of the superclass or you write a default constructor of the superclass. Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 12

Example 1 public class Character { 2 private String name; 3 // Constructor 4 public Character(String name){ 5 this.name = name; 6 } 7 8 public String introduction(){ 0 return My name is + name; 10 } 11 } 1 public class Gaul extends Character { 2 3 public Gaul(String name){ 4 super(name); 5 } 6 7 public String introduction(){ 8 return super.introduction() + I am a Gaul ; 9 } 10 11 public static void main(string[] args){ 12 Gaul asterix = new Gaul( Astérix ); 13 System.out.println( asterix.introduction()); 14 } 15 } Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 13

Operator instanceof We can check whether an instance is a member of a class. (sometimes, we may not know the precise type of a variable) 1 public class Character {... } 1 public class Gaul extends Character {... } 1 public class IndomitableGaul extends Gaul {... } 1 public class Roman extends Character {... } 2... 5 public static void main(string[] args){ 6 IndomitableGaul asterix = new IndomitableGaul(); 7 System.out.println( asterix instanceof Character); 8 System.out.println( asterix instanceof Gaul); 9 System.out.println( asterix instanceof Roman); Astérix is a character, a Gaul, and even an indomitable Gaul. Of course, he is not a Roman! Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 14

Operator instanceof We can check whether an instance is a member of a class. (sometimes, we may not know the precise type of a variable) 1 public class Character {... } 1 public class Gaul extends Character {... } 1 public class IndomitableGaul extends Gaul {... } 1 public class Roman extends Character {... } 2... 5 public static void main(string[] args){ 6 IndomitableGaul asterix = new IndomitableGaul(); 7 System.out.println( asterix instanceof Character); 8 System.out.println( asterix instanceof Gaul); 9 System.out.println( asterix instanceof Roman); Astérix is a character, a Gaul, and even an indomitable Gaul. Of course, he is not a Roman! Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 15

Operator instanceof We can check whether an instance is a member of a class. (sometimes, we may not know the precise type of a variable) 1 public class Character {... } 1 public class Gaul extends Character {... } 1 public class IndomitableGaul extends Gaul {... } 1 public class Roman extends Character {... } 2... 5 public static void main(string[] args){ 6 IndomitableGaul asterix = new IndomitableGaul(); 7 System.out.println( asterix instanceof Character); 8 System.out.println( asterix instanceof Gaul); 9 System.out.println( asterix instanceof Roman); Astérix is a character, a Gaul, and even an indomitable Gaul. Of course, he is not a Roman! Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 16

Operator instanceof We can check whether an instance is a member of a class. (sometimes, we may not know the precise type of a variable) 1 public class Character {... } 1 public class Gaul extends Character {... } 1 public class IndomitableGaul extends Gaul {... } 1 public class Roman extends Character {... } 2... 5 public static void main(string[] args){ 6 IndomitableGaul asterix = new IndomitableGaul(); 7 System.out.println( asterix instanceof Character); 8 System.out.println( asterix instanceof Gaul); 9 System.out.println( asterix instanceof Roman); Astérix is a character, a Gaul, and even an indomitable Gaul. Of course, he is not a Roman! Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 17

Polymorphism From the previous example, it seems Astérix has many types : this is what is called polymorphism : the fact that a variable may have several types. This allows the manipulation of objects that all share the same superclass! 1 Character asterix = new Gaul( Astérix ); 1 Gaul obelix = new Gaul( Obélix ); 2 Gaul asterix = new Gaul( Astérix ); 3 Character cleopatre = new Character( Cléopâtre ) ; 3 Character[] distribution= new Character[3]; 4 distribution[0]= asterix; 5 distribution[1]= obelix; 6 distribution[2]= cleopatre; Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 18

Polymorphism 1 Character asterix = new Gaul( Astérix ); In this example asterix is declared as a Character, even though the real object stored in memory is a Gaul. As the variable is declared as a Character, we can only call methods from the class Character and not specific method of a subclass such as Gaul. For example : asterix.isaffraidoftheskyfallingonhishead(); is not allowed! Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 19

Late binding The three classes have an introduction() method Java chooses the appropriate method at execution time. dynamic binding. At compilation time, Java checks whether the method is from the Character class or one of its superclass If an objecto est declared of type T, we call only call methods from class T or its superclasses on object o! But the executed method is the one of the class o was constructed from 1 public class Character { 2... 3 public String introduction(){ 4 return my name is +name; 5 } 6 } 1 public class Gaul extends Character { 2 public Gaul(String name){ super(name);} 3 @Override 4 public String introduction(){ 5 return super.introduction() + I am a Gaul ; 6 } 7 } 1 public class Roman extends Character { 2 public Roman(String name){ super(name);} 3 @Override 4 public String introduction(){ 5 return super.introduction() + romanus sum. ; 6 } 7 } 1 public static void main(string[] args){ 2 Random generator = new Random(); 3 Character mystere; 4 if (generator.nextboolean()) 5 mystere = new Gaul( Astérix ); 6 else 7 mystere = new Roman( Jules ); 8 System.out.println(mystere.introduction()); 9 } } Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 20

final keyword used for a class : this class cannot have a subclass security example : class String for a method : this method cannot be overriden in a subclass we force that the method of the superclass is the only possible behaviour for a variable : it will not be modified once the execution of the constructor is over Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 21

Object is the superclass of all objects Modifier and Type protected Object boolean protected void Class<?> int String Method Description clone() Creates and returns a copy of this object. equals(object obj) Indicates whether some other object is "equal to" this one. finalize() Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. getclass() Returns the runtime class of this Object. hashcode() Returns a hash code value for the object. tostring() Returns a string reintroduction of the object. Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 22

Object is the superclass of all objects : consequence if you do not redefine a method of Object, it is the implementation of the method in the Object class that is executed. tostring() : The tostring method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character @, and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of: getclass().getname() + @ + Integer.toHexString(hashCode()) clone() : this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation. Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 23

Object is the superclass of all objects : consequence equals() The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true). it is your job to write the appropriate code for equality! How do you consider two instances of a class are equal. warning : boolean equals(object obj) Note that the argument obj is of type Object. If you want to redefine correctly the method equals, you must use this signature. you can first check if obj has the right type if so, the cast is safe and you can check whether the properties of obj match the ones of the current object. Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 24

Let s apply Do exercise 1. Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 25

Abstract methods and abstract classes Context : If we give some thoughts, the Character will never be instantiated as we will always use a subclass (e.g. Roman, Gaul, Animals, etc). For some methods, we will always use the method of the subclass : there is no need to have an implementation! But having the declaration may be very useful! Declaring without implementing the method will force the implementation in a subclass (maybe not the direct subclass) Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 26

Abstract methods and abstract classes Context : If we give some thoughts, the Character will never be instantiated as we will always use a subclass (e.g. Roman, Gaul, Animals, etc). For some methods, we will always use the method of the subclass : there is no need to have an implementation! But having the declaration may be very useful! Declaring without implementing the method will force the implementation in a subclass (maybe not the direct subclass) Solution : We use the keyword abstract An abstract method never has a body must be implemented in a subclass an abstract class has at least an abstact method can not be instantiated! Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 27

Example 1 public abstract class Character { 2 3 String name; 4 5 public Character(String name); 6 7 // to be defined in subclasses 8 public abstract void introduction(); 9 10 // shared by all subclasses 11 public void mynameis(){ 12 System.out.println( my name is + name); 13 } 14 } N.B. even though Character is abstact, it can have a constructor this is useful if one wants to initialise some variables before using the object Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 28

Interfaces In Java, a class can inherit from a single class It woud be useful to inherit from multiple entities. In Java, interfaces are the way to go! We can view an interface as a norm : to follow a norm a class must implement the method declared in the interface we say a classimplements an interface. a class may implement multiple interfaces. 1 [public] interface <interface name> 2 [extends <interface name 1> <interface name 2>... ] { 3 // declaration of methods 4 // we can have static methods or variables } 4 } Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 29

Interfaces a method without body in an interface is implicitly abstract (i.e.no need to add the keywor abstract) Any variable is static and final. 1 public interface Fighter { 2 public void attack(character p); 3 public void defend(fighter c); 4 } 1 public class IndomitableGaul implements Fighter { 2... 3 public void attack(character p){ 4 magicpotion.drink(); 5 while(p.isstanding()) 6 punch(p); 7 } 8 9 public void defend(fighter c){ 10 dodge(); 11 attack(c); 12 } 13 } Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 30