SlideShare uma empresa Scribd logo
1 de 22
Programming in Java
5-day workshop
OOP Polymorphism
Matt Collison
JP Morgan Chase 2021
PiJ3.2: OOP Polymorphism
Four principles of OOP:
1.Encapsulation – defining a class
2.Abstraction – modifying the objects
3.Inheritance – extending classes
4.Polymorphism – implementing interfaces
How do we achieve abstraction through OOP?
• Classes and objects: The first order of abstraction. class new
• There are lots of things that the same but with different attribute values.
• For example people – we all have a name, a height, we have interests and friends. Think of a
social media platform. Everyone has a profile but everyone’s profile is unique.
• Class inheritance: The second order of abstraction extends super instanceof
• The definitions for things can share common features.
• For example the administrator account and a user account both require a username,
password and contact details. Each of these account would extend a common ‘parent’
account definition.
• Polymorphism: The third order of abstraction interface implements @Override
• The definitions for things can share features but complete them in different ways to achieve
different behaviours. For example an e-commerce store must have a database binding, a
layout schema for the UI but the specific implementations are unique. These aren’t just
different values but different functions.
Interfaces
public interface ParentInterfaceIdentifier{
}
public class Identifier implements
ParentInterfaceIdentifier {
}
• An interface behaves like a programming ‘contract’
• Client: provides the interface
• Service provider: provides implementation(s)
Class relations
class class interface
class interface interface
extends implements implements
Defining an interface
• An interface is a reference type, similar to a class, which variables can be declared
as (although not instantiated).
Contains:
• Constructors:
• No constructor(s)
• Attributes:
• Only static constants e.g. int A = 1; //implicitly public, static, and final
• Methods:
• Abstract methods e.g. double area(); //implicitly public and abstract
• Since Java 8, two types of non-abstract (i.e. concrete) methods are allowed.
• static void help(){...} //with body
• default void newFunction(){...} //with body
Rules of interfaces
• Interfaces cannot be instantiated.
• Interfaces cannot contain instance fields.
• If any non-abstract class implements an interface, it must implement
all the abstract methods in the interface. Otherwise, the class must
be declared as abstract.
Inheritance recap
• Superclass or base, parent class
• Subclass or derived, child, extended class
• Single inheritance only – there can only be one superclass for each
class. This creates a hierarchy or tree.
Example: the abstract Shape class
public abstract class Shape {
private String colour;
public Shape(String colour){ this.colour = colour; }
public Shape(){ colour = "black"; }
// Getters and Setters
public void setColour(String colour) { this.colour = colour; }
public String getColour() { return colour; }
// Two abstract methods
public abstract double area();
public abstract double perimeter();
}
Example: the Shape interface
/** * A Shape interface */
public interface Shape {
// Two abstract methods
double area();
double perimeter();
// A default method with body
default void printAreaPerimeter() {
System.out.println( area() );
System.out.println( perimeter() );
}
}
Example: the Shape interface
public class Rectangle implements Shape {
private double width, height;
private String colour;
public Rectangle(double width, double height, String colour) {
this.colour = colour; this.width = width; this.height = height;
}
@Override // informing compiler of intended override
public double area() { return width * height; }
@Override // informing compiler of intended override
public double perimeter() { return 2.0 * (width + height); }
// ... other methods
}
Example: the Shape interface
public class ShapeApp {
public static void main(String[] args) {
//declare them all shapes, but instantiate them
//with different implementation classes
Shape s1, s2, s3;
s1 = new Rectangle(3.0,4.0,"green");
System.out.println(s1);
s2 = new Rectangle(3.0,4.0,"green");
s2.printAreaPerimeter(); //call the default method
s3 = new Triangle(3.0,4.0,5.0,"green");
System.out.println(s3.toString());
System.out.println(s1.equals(s2));
System.out.println(s3.equals(s2));
}
}
//Rectangle@7b23ec81
//true
//false
Implementing multiple interfaces
• A class can implement multiple interfaces:
class PowerPoint implements Printable, Showable{...}
• A class can both extend one class and implement multiple interfaces:
class PowerPoint extends OfficeSoftware implements Printable,
Showable{...} //first extends, then implements
Implementing multiple interfaces
// A demo for implementing multiple interfaces
interface Printable { void print(); //implicitly public abstract }
interface Showable { void show(); //implicitly public abstract }
public class PowerPoint implements Printable, Showable {
public void print() { System.out.println("Print the PPT"); }
public void show() { System.out.println("Show the PPT"); }
public static void main(String args[]) {
PowerPoint obj = new PowerPoint();
obj.print();
obj.show();
}
}
Implementing multiple interfaces
Q: Java does not support multiple inheritance through classes, but
allows implementing multiple interfaces. Why?
A: Ambiguity may occur in the case of class for the concrete method to
use, but not for an interface.
• For example, there will be no conflicts if both the Printable interface
and Showable interface has the same method: print().
• A slight wrinkle when there are conflicting default methods...
Abstract classes vs. Interfaces
Similarity:
• Both can not be instantiated.
• Both can include abstract methods, i.e., only with method signature,
no implementation.
• Both are usually used as a general type parameter — when a variable
is declared — while the actual action of the method depends on the
subclasses, i.e., polymorphism
Abstract classes vs. Interfaces
Difference (recall the class members):
• Constructors ...
• Attributes ...
• Methods ...
Rule of thumb
• Program to an interface, not an implementation.
• That is, make references at the superclass/interface; substitute with
subclass instances; and invoke methods defined in the
superclass/interface only.
void someMethod(Shape shape){
double a = shape.area();
double b = shape.perimeter();
...
}
Rule of thumb
• Program to an interface, not an implementation.
• This is a powerful tool for abstraction.
• The separation of interface and implementation enables better
software design, and ease in expansion.
• Specialised implementors can be employed and instantiated
dynamically depending on context – no need to modify existing
codebase.
Summary
Keywords:
• interface
• implements
• default
• A class can extend at most one class, but implement multiple
interfaces
• abstract class vs. interface
Learning resources
The workshop homepage
https://mcollison.github.io/JPMC-java-intro-2021/
The course materials
https://mcollison.github.io/java-programming-foundations/
• Session worksheets – updated each week
Additional resources
• Think Java: How to think like a computer scientist
• Allen B Downey (O’Reilly Press)
• Available under Creative Commons license
• https://greenteapress.com/wp/think-java-2e/
• Oracle central Java Documentation –
https://docs.oracle.com/javase/8/docs/api/
• Other sources:
• W3Schools Java - https://www.w3schools.com/java/
• stack overflow - https://stackoverflow.com/
• Coding bat - https://codingbat.com/java

Mais conteúdo relacionado

Mais procurados

Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in JavaWeek9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Javakjkleindorfer
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in javaElizabeth alexander
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classesFajar Baskoro
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objectsmaznabili
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword pptVinod Kumar
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Javabackdoor
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in javaAtul Sehdev
 
Seminar on java
Seminar on javaSeminar on java
Seminar on javashathika
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteTushar B Kute
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysDevaKumari Vijay
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3Mahmoud Alfarra
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 

Mais procurados (20)

Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in JavaWeek9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Java
 
Classes and objects in java
Classes and objects in javaClasses and objects in java
Classes and objects in java
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
Object and class
Object and classObject and class
Object and class
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in java
 
Seminar on java
Seminar on javaSeminar on java
Seminar on java
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Java basic
Java basicJava basic
Java basic
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 

Semelhante a Pi j3.2 polymorphism

Semelhante a Pi j3.2 polymorphism (20)

Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oop
 
Better Understanding OOP using C#
Better Understanding OOP using C#Better Understanding OOP using C#
Better Understanding OOP using C#
 
Abstraction in Java: Abstract class and Interfaces
Abstraction in  Java: Abstract class and InterfacesAbstraction in  Java: Abstract class and Interfaces
Abstraction in Java: Abstract class and Interfaces
 
LectureNotes-02-DSA
LectureNotes-02-DSALectureNotes-02-DSA
LectureNotes-02-DSA
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
8abstact class in c#
8abstact class in c#8abstact class in c#
8abstact class in c#
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
Inheritance
InheritanceInheritance
Inheritance
 
Abstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAbstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and Interfaces
 
Java 6.pptx
Java 6.pptxJava 6.pptx
Java 6.pptx
 
Lecture 8 Library classes
Lecture 8 Library classesLecture 8 Library classes
Lecture 8 Library classes
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
core_java.ppt
core_java.pptcore_java.ppt
core_java.ppt
 
Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
Java Basics
Java BasicsJava Basics
Java Basics
 
javainterface
javainterfacejavainterface
javainterface
 

Mais de mcollison

Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliabilitymcollison
 
Pi j4.1 packages
Pi j4.1 packagesPi j4.1 packages
Pi j4.1 packagesmcollison
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritancemcollison
 
Pi j3.4 data-structures
Pi j3.4 data-structuresPi j3.4 data-structures
Pi j3.4 data-structuresmcollison
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objectsmcollison
 
Pi j2.2 classes
Pi j2.2 classesPi j2.2 classes
Pi j2.2 classesmcollison
 
Pi j1.0 workshop-introduction
Pi j1.0 workshop-introductionPi j1.0 workshop-introduction
Pi j1.0 workshop-introductionmcollison
 
Pi j1.4 loops
Pi j1.4 loopsPi j1.4 loops
Pi j1.4 loopsmcollison
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operatorsmcollison
 
Pi j1.2 variable-assignment
Pi j1.2 variable-assignmentPi j1.2 variable-assignment
Pi j1.2 variable-assignmentmcollison
 
Pi j1.1 what-is-java
Pi j1.1 what-is-javaPi j1.1 what-is-java
Pi j1.1 what-is-javamcollison
 

Mais de mcollison (11)

Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
Pi j4.1 packages
Pi j4.1 packagesPi j4.1 packages
Pi j4.1 packages
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritance
 
Pi j3.4 data-structures
Pi j3.4 data-structuresPi j3.4 data-structures
Pi j3.4 data-structures
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
Pi j2.2 classes
Pi j2.2 classesPi j2.2 classes
Pi j2.2 classes
 
Pi j1.0 workshop-introduction
Pi j1.0 workshop-introductionPi j1.0 workshop-introduction
Pi j1.0 workshop-introduction
 
Pi j1.4 loops
Pi j1.4 loopsPi j1.4 loops
Pi j1.4 loops
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operators
 
Pi j1.2 variable-assignment
Pi j1.2 variable-assignmentPi j1.2 variable-assignment
Pi j1.2 variable-assignment
 
Pi j1.1 what-is-java
Pi j1.1 what-is-javaPi j1.1 what-is-java
Pi j1.1 what-is-java
 

Último

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 

Último (20)

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 

Pi j3.2 polymorphism

  • 1. Programming in Java 5-day workshop OOP Polymorphism Matt Collison JP Morgan Chase 2021 PiJ3.2: OOP Polymorphism
  • 2. Four principles of OOP: 1.Encapsulation – defining a class 2.Abstraction – modifying the objects 3.Inheritance – extending classes 4.Polymorphism – implementing interfaces
  • 3. How do we achieve abstraction through OOP? • Classes and objects: The first order of abstraction. class new • There are lots of things that the same but with different attribute values. • For example people – we all have a name, a height, we have interests and friends. Think of a social media platform. Everyone has a profile but everyone’s profile is unique. • Class inheritance: The second order of abstraction extends super instanceof • The definitions for things can share common features. • For example the administrator account and a user account both require a username, password and contact details. Each of these account would extend a common ‘parent’ account definition. • Polymorphism: The third order of abstraction interface implements @Override • The definitions for things can share features but complete them in different ways to achieve different behaviours. For example an e-commerce store must have a database binding, a layout schema for the UI but the specific implementations are unique. These aren’t just different values but different functions.
  • 4. Interfaces public interface ParentInterfaceIdentifier{ } public class Identifier implements ParentInterfaceIdentifier { } • An interface behaves like a programming ‘contract’ • Client: provides the interface • Service provider: provides implementation(s)
  • 5. Class relations class class interface class interface interface extends implements implements
  • 6. Defining an interface • An interface is a reference type, similar to a class, which variables can be declared as (although not instantiated). Contains: • Constructors: • No constructor(s) • Attributes: • Only static constants e.g. int A = 1; //implicitly public, static, and final • Methods: • Abstract methods e.g. double area(); //implicitly public and abstract • Since Java 8, two types of non-abstract (i.e. concrete) methods are allowed. • static void help(){...} //with body • default void newFunction(){...} //with body
  • 7. Rules of interfaces • Interfaces cannot be instantiated. • Interfaces cannot contain instance fields. • If any non-abstract class implements an interface, it must implement all the abstract methods in the interface. Otherwise, the class must be declared as abstract.
  • 8. Inheritance recap • Superclass or base, parent class • Subclass or derived, child, extended class • Single inheritance only – there can only be one superclass for each class. This creates a hierarchy or tree.
  • 9. Example: the abstract Shape class public abstract class Shape { private String colour; public Shape(String colour){ this.colour = colour; } public Shape(){ colour = "black"; } // Getters and Setters public void setColour(String colour) { this.colour = colour; } public String getColour() { return colour; } // Two abstract methods public abstract double area(); public abstract double perimeter(); }
  • 10. Example: the Shape interface /** * A Shape interface */ public interface Shape { // Two abstract methods double area(); double perimeter(); // A default method with body default void printAreaPerimeter() { System.out.println( area() ); System.out.println( perimeter() ); } }
  • 11. Example: the Shape interface public class Rectangle implements Shape { private double width, height; private String colour; public Rectangle(double width, double height, String colour) { this.colour = colour; this.width = width; this.height = height; } @Override // informing compiler of intended override public double area() { return width * height; } @Override // informing compiler of intended override public double perimeter() { return 2.0 * (width + height); } // ... other methods }
  • 12. Example: the Shape interface public class ShapeApp { public static void main(String[] args) { //declare them all shapes, but instantiate them //with different implementation classes Shape s1, s2, s3; s1 = new Rectangle(3.0,4.0,"green"); System.out.println(s1); s2 = new Rectangle(3.0,4.0,"green"); s2.printAreaPerimeter(); //call the default method s3 = new Triangle(3.0,4.0,5.0,"green"); System.out.println(s3.toString()); System.out.println(s1.equals(s2)); System.out.println(s3.equals(s2)); } } //Rectangle@7b23ec81 //true //false
  • 13. Implementing multiple interfaces • A class can implement multiple interfaces: class PowerPoint implements Printable, Showable{...} • A class can both extend one class and implement multiple interfaces: class PowerPoint extends OfficeSoftware implements Printable, Showable{...} //first extends, then implements
  • 14. Implementing multiple interfaces // A demo for implementing multiple interfaces interface Printable { void print(); //implicitly public abstract } interface Showable { void show(); //implicitly public abstract } public class PowerPoint implements Printable, Showable { public void print() { System.out.println("Print the PPT"); } public void show() { System.out.println("Show the PPT"); } public static void main(String args[]) { PowerPoint obj = new PowerPoint(); obj.print(); obj.show(); } }
  • 15. Implementing multiple interfaces Q: Java does not support multiple inheritance through classes, but allows implementing multiple interfaces. Why? A: Ambiguity may occur in the case of class for the concrete method to use, but not for an interface. • For example, there will be no conflicts if both the Printable interface and Showable interface has the same method: print(). • A slight wrinkle when there are conflicting default methods...
  • 16. Abstract classes vs. Interfaces Similarity: • Both can not be instantiated. • Both can include abstract methods, i.e., only with method signature, no implementation. • Both are usually used as a general type parameter — when a variable is declared — while the actual action of the method depends on the subclasses, i.e., polymorphism
  • 17. Abstract classes vs. Interfaces Difference (recall the class members): • Constructors ... • Attributes ... • Methods ...
  • 18. Rule of thumb • Program to an interface, not an implementation. • That is, make references at the superclass/interface; substitute with subclass instances; and invoke methods defined in the superclass/interface only. void someMethod(Shape shape){ double a = shape.area(); double b = shape.perimeter(); ... }
  • 19. Rule of thumb • Program to an interface, not an implementation. • This is a powerful tool for abstraction. • The separation of interface and implementation enables better software design, and ease in expansion. • Specialised implementors can be employed and instantiated dynamically depending on context – no need to modify existing codebase.
  • 20. Summary Keywords: • interface • implements • default • A class can extend at most one class, but implement multiple interfaces • abstract class vs. interface
  • 21. Learning resources The workshop homepage https://mcollison.github.io/JPMC-java-intro-2021/ The course materials https://mcollison.github.io/java-programming-foundations/ • Session worksheets – updated each week
  • 22. Additional resources • Think Java: How to think like a computer scientist • Allen B Downey (O’Reilly Press) • Available under Creative Commons license • https://greenteapress.com/wp/think-java-2e/ • Oracle central Java Documentation – https://docs.oracle.com/javase/8/docs/api/ • Other sources: • W3Schools Java - https://www.w3schools.com/java/ • stack overflow - https://stackoverflow.com/ • Coding bat - https://codingbat.com/java