SlideShare a Scribd company logo
1 of 22
Μάθημα 5ο
Polymorphism and Interfaces
A quick review in inheritance and polymorphism
1. We have avoided code duplication
2. We have overridden some methods that need
specific implementation by the subclasses
3. We created a polymorphic design, so that we
can use Animal references as arguments for any
subtype class even those that haven’t been
created yet.
4. By establishing a common protocol in the
inheritance tree we buy more extendibility for
our code-design.
Abstract and concrete classes
• It doesn’t make sense for some
superclasses to be instantiated.
• We still need superclasses for the
purpose of inheritance and
polymorphism but it has no meaning a
generic use of them.
• There is a simple way to stop a class
from being instantiated and that is the
declaration abstract
• Abstract classes can still be used as
references.
• Only the less abstract subclasses -the
concrete classes -should be
Instantiated.
Syntax
abstract class Canine extends Animal {
public void Roam() { }
}
Abstract methods
• You might decide that some behaviors of an abstract class don’t make sense unless
they’re implemented by subclasses.
• An abstract class means the class must be extended.
• An abstract method means the method must be overridden.
• An abstract method has no body .
• If you declare an abstract method, you MUST mark the class abstract as well. You
can’t have an abstract method in a non-abstract class.
• An abstract class can still have non-abstract methods.
SYNTAX
public abstract void eat();
You must implement all abstract methods
 Implementing an abstract method is like overriding a method
 So you have to create a non-abstract method with the same signature and a return
type that is compatible to the return type of the abstract method.
 The first concrete class in the inheritance tree must provide a body to an abstract
class
 However it can avoid this “responsibility” by being abstract itself.
Polymorphism in action
 Lets say we want to build our
own ArrayList that holds Dog
objects
 We’ll use an array of dogs
 Implement an add method
What about if we want to keep Cats too
1. Make a separate class , MyCatList to hold
Cat objects
2. Make a single class DogAndCatList that
keeps two different arrays as instance
variables and has two add methods
3. Make an Animal List class, that takes any
Animal subtype
Can we make a class generic enough to
take anything?
 Every class in Java extends class
Object the superclass of everything
 We were writing subclasses of class
Object from the beginning of time.
 Without a common superclass we
wouldn't be able to create our
custom types of classes
Using polymorphic references of type Object has a price
Everything comes out of an ArrayList<Object> as a reference of type Object regardless of
what the actual object is , or what the reference type was when you added the object to the
list
Some further implications
Object o = al.get(index);
int i = o.hashCode();
o.bark(); // it won’t compile
Is it a problem to have to use an Object
reference variable to refer to a subclass object?
The compiler decides whether you
can call a method based on the
reference type, not the actual
object type.
A first glance at the object form in the Heap
• An object contains everything it inherits
from each of its superclasses .That means
that every object is also an instance of
class Object so it can be treated that way.
• If a reference is like a remote control, the
remote control takes on more buttons as
you move down the inheritance tree. So
an Object reference has fewer buttons
than the subtype reference “remote
control”
Casting an object reference back to its real type.
If you are not sure of the class subtype you can
use the instanceof operator to check.
if (o instanceof Dog) {
Dog d = (Dog) o;
}
• If you need to treat the object as its subtype
you need a reference (remote control) to
access all its specific methods.
• You can make a new subtype reference to
the object by copying the Object reference
and forcing that copy to go into the subtype
reference variable
• The above procedure is called cast.
Specifications changed. Is our design reusable?
• Imagine that you have to use your previous design for a PetShop program.
• You have to implement Pet behaviors like beFriendly() and play().
• You could simply add some methods more methods without breaking any
existing method implementation.
• But where would you implement the new methods and why? What are the
possible problems that can occur?
Let’s see look closer to some scenarios
Put the new methods in the Superclass
Override the methods in the subclasses’ implementation
The methods go ONLY in the classes where they belong
What the ideal
approach would be?
 A way to have pet behavior in just the
pet classes
 A way to guarantee that all pet classes
have all of the same methods defined
(same name, same arguments, same
return types, no missing methods,
etc.), without having to cross your
fingers and hope all the programmers
get it right.
 A way to take advantage of
polymorphism so that all pets can
have their pet methods called, without
having to use arguments, return types,
and arrays for each and every pet
class.
The previous class
diagram is not permitted
• Multiple Inheritance is not
supported in Java since it can
lead to severe problems
• The most serious is the so
called Deadly Diamond of
Death.
So how do we handle the
whole thing with Pet/Animal
class?
Interface gives us the solution
• A Java interface solves multiple
inheritance problem by giving the
polymorphic benefits without the
DDD.
• The way that interfaces elect to
side-step DDD is by keeping all
the methods abstract.
• That way the subclass that has to
play that role must implement all
the methods (provide body)
SYNTAX
To DEFINE an interface:
public interface Pet {...}
To IMPLEMENT an interface:
public class Dog extends Canine implements Pet {...}
Advantages and characteristics of an Interface
• Interfaces buy us polymorphism and flexibility.
• You can pass anything that implements an interface as an argument or a return type.
• Even from a completely different inheritance tree
• You treat an object by the role it plays and not the class that it was instantiated.
• A class can implement multiple interfaces
Things to think over when you design your class diagram
How do you know whether to make a class, a
subclass, an abstract class, or an interface?
1. Make a class that doesn’t extend
anything(other than Object) when your
new class doesn’t pass the IS-A test for
any other type. Make a subclass (in other
words, extend a class)only when you
need to make a more specific version of
a class and need to override or add new
behaviors.
2. Use an abstract class when you want to
define a template for a group of
subclasses, and you have at least some
implementation code that all subclasses
could use. Make the class abstract when
you want to guarantee that nobody can
make objects of that type.
3. Use an interface when you want to
define a role that other classes can play,
regardless of where those classes are in
the inheritance tree.
Bullet Points

More Related Content

What's hot

What's hot (14)

Generics of JAVA
Generics of JAVAGenerics of JAVA
Generics of JAVA
 
ITFT - Java
ITFT - JavaITFT - Java
ITFT - Java
 
Logic and Coding of Java Interfaces & Swing Applications
Logic and Coding of Java Interfaces & Swing ApplicationsLogic and Coding of Java Interfaces & Swing Applications
Logic and Coding of Java Interfaces & Swing Applications
 
Me, my self and IPython
Me, my self and IPythonMe, my self and IPython
Me, my self and IPython
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 ee
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
 
Lecture 1 - Objects and classes
Lecture 1 - Objects and classesLecture 1 - Objects and classes
Lecture 1 - Objects and classes
 
Type system
Type systemType system
Type system
 
Keywords and classes
Keywords and classesKeywords and classes
Keywords and classes
 
OOP Concepets and UML Class Diagrams
OOP Concepets and UML Class DiagramsOOP Concepets and UML Class Diagrams
OOP Concepets and UML Class Diagrams
 
Inheritance
InheritanceInheritance
Inheritance
 
Week 2: Getting Your Hands Dirty – Part 2
Week 2: Getting Your Hands Dirty – Part 2Week 2: Getting Your Hands Dirty – Part 2
Week 2: Getting Your Hands Dirty – Part 2
 
Enumerables
EnumerablesEnumerables
Enumerables
 
Methods and constructors
Methods and constructorsMethods and constructors
Methods and constructors
 

Viewers also liked

Planes de produccion
Planes de produccionPlanes de produccion
Planes de produccionGaboMoreno21
 
Taller práctico 10 claves para la implementación de tendencias y enfoques inn...
Taller práctico 10 claves para la implementación de tendencias y enfoques inn...Taller práctico 10 claves para la implementación de tendencias y enfoques inn...
Taller práctico 10 claves para la implementación de tendencias y enfoques inn...Arturo Marín
 
Srpsko carstvo i pad srpskog carstva
Srpsko carstvo i pad srpskog carstvaSrpsko carstvo i pad srpskog carstva
Srpsko carstvo i pad srpskog carstvaDušan Novakov
 
変動する世界における科学技術外交の役割と課題
変動する世界における科学技術外交の役割と課題変動する世界における科学技術外交の役割と課題
変動する世界における科学技術外交の役割と課題scirexcenter
 
『政策のための科学』の発展にむけて
『政策のための科学』の発展にむけて『政策のための科学』の発展にむけて
『政策のための科学』の発展にむけてscirexcenter
 
Darren shaw proximity is the new top local search ranking factor - local or...
Darren shaw   proximity is the new top local search ranking factor - local or...Darren shaw   proximity is the new top local search ranking factor - local or...
Darren shaw proximity is the new top local search ranking factor - local or...Darren Shaw
 
LA LOI DE FINANCES 2017 !
LA LOI DE FINANCES 2017 !LA LOI DE FINANCES 2017 !
LA LOI DE FINANCES 2017 !FIDAQUITAINE
 

Viewers also liked (16)

Planes de produccion
Planes de produccionPlanes de produccion
Planes de produccion
 
Taller práctico 10 claves para la implementación de tendencias y enfoques inn...
Taller práctico 10 claves para la implementación de tendencias y enfoques inn...Taller práctico 10 claves para la implementación de tendencias y enfoques inn...
Taller práctico 10 claves para la implementación de tendencias y enfoques inn...
 
Geethasri Resume
Geethasri ResumeGeethasri Resume
Geethasri Resume
 
Practica nº 1
Practica nº 1  Practica nº 1
Practica nº 1
 
Innovation_Imperative_Erion_Nako_KEMBA_2017
Innovation_Imperative_Erion_Nako_KEMBA_2017Innovation_Imperative_Erion_Nako_KEMBA_2017
Innovation_Imperative_Erion_Nako_KEMBA_2017
 
Valores del abogado
Valores del abogadoValores del abogado
Valores del abogado
 
10277678
1027767810277678
10277678
 
Mapa mental%2c la comunicacion.
Mapa mental%2c la comunicacion.Mapa mental%2c la comunicacion.
Mapa mental%2c la comunicacion.
 
Srpsko carstvo i pad srpskog carstva
Srpsko carstvo i pad srpskog carstvaSrpsko carstvo i pad srpskog carstva
Srpsko carstvo i pad srpskog carstva
 
変動する世界における科学技術外交の役割と課題
変動する世界における科学技術外交の役割と課題変動する世界における科学技術外交の役割と課題
変動する世界における科学技術外交の役割と課題
 
『政策のための科学』の発展にむけて
『政策のための科学』の発展にむけて『政策のための科学』の発展にむけて
『政策のための科学』の発展にむけて
 
ENGLISH PRESENTATION
ENGLISH PRESENTATIONENGLISH PRESENTATION
ENGLISH PRESENTATION
 
La familia
La familiaLa familia
La familia
 
Darren shaw proximity is the new top local search ranking factor - local or...
Darren shaw   proximity is the new top local search ranking factor - local or...Darren shaw   proximity is the new top local search ranking factor - local or...
Darren shaw proximity is the new top local search ranking factor - local or...
 
LA LOI DE FINANCES 2017 !
LA LOI DE FINANCES 2017 !LA LOI DE FINANCES 2017 !
LA LOI DE FINANCES 2017 !
 
Traditionalapproach
TraditionalapproachTraditionalapproach
Traditionalapproach
 

Similar to Java interfaces

Similar to Java interfaces (20)

C#
C#C#
C#
 
Review oop and ood
Review oop and oodReview oop and ood
Review oop and ood
 
Java session2
Java session2Java session2
Java session2
 
C# interview quesions
C# interview quesionsC# interview quesions
C# interview quesions
 
Java programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- InheritanceJava programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- Inheritance
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interview
 
Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
 
Java unit 7
Java unit 7Java unit 7
Java unit 7
 
Object oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxObject oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptx
 
Oops
OopsOops
Oops
 
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
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oop
 
Object Oriented Programming - Polymorphism and Interfaces
Object Oriented Programming - Polymorphism and InterfacesObject Oriented Programming - Polymorphism and Interfaces
Object Oriented Programming - Polymorphism and Interfaces
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptx
 
Ruby object model
Ruby object modelRuby object model
Ruby object model
 
Ruby Interview Questions
Ruby Interview QuestionsRuby Interview Questions
Ruby Interview Questions
 
ACM init() Day 6
ACM init() Day 6ACM init() Day 6
ACM init() Day 6
 
Chapter 8 java
Chapter 8 javaChapter 8 java
Chapter 8 java
 
Unit 3 Java
Unit 3 JavaUnit 3 Java
Unit 3 Java
 

Recently uploaded

Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 

Recently uploaded (20)

Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 

Java interfaces

  • 2. A quick review in inheritance and polymorphism 1. We have avoided code duplication 2. We have overridden some methods that need specific implementation by the subclasses 3. We created a polymorphic design, so that we can use Animal references as arguments for any subtype class even those that haven’t been created yet. 4. By establishing a common protocol in the inheritance tree we buy more extendibility for our code-design.
  • 3. Abstract and concrete classes • It doesn’t make sense for some superclasses to be instantiated. • We still need superclasses for the purpose of inheritance and polymorphism but it has no meaning a generic use of them. • There is a simple way to stop a class from being instantiated and that is the declaration abstract • Abstract classes can still be used as references. • Only the less abstract subclasses -the concrete classes -should be Instantiated. Syntax abstract class Canine extends Animal { public void Roam() { } }
  • 4. Abstract methods • You might decide that some behaviors of an abstract class don’t make sense unless they’re implemented by subclasses. • An abstract class means the class must be extended. • An abstract method means the method must be overridden. • An abstract method has no body . • If you declare an abstract method, you MUST mark the class abstract as well. You can’t have an abstract method in a non-abstract class. • An abstract class can still have non-abstract methods. SYNTAX public abstract void eat();
  • 5. You must implement all abstract methods  Implementing an abstract method is like overriding a method  So you have to create a non-abstract method with the same signature and a return type that is compatible to the return type of the abstract method.  The first concrete class in the inheritance tree must provide a body to an abstract class  However it can avoid this “responsibility” by being abstract itself.
  • 6. Polymorphism in action  Lets say we want to build our own ArrayList that holds Dog objects  We’ll use an array of dogs  Implement an add method
  • 7. What about if we want to keep Cats too 1. Make a separate class , MyCatList to hold Cat objects 2. Make a single class DogAndCatList that keeps two different arrays as instance variables and has two add methods 3. Make an Animal List class, that takes any Animal subtype
  • 8. Can we make a class generic enough to take anything?  Every class in Java extends class Object the superclass of everything  We were writing subclasses of class Object from the beginning of time.  Without a common superclass we wouldn't be able to create our custom types of classes
  • 9. Using polymorphic references of type Object has a price Everything comes out of an ArrayList<Object> as a reference of type Object regardless of what the actual object is , or what the reference type was when you added the object to the list
  • 10. Some further implications Object o = al.get(index); int i = o.hashCode(); o.bark(); // it won’t compile Is it a problem to have to use an Object reference variable to refer to a subclass object? The compiler decides whether you can call a method based on the reference type, not the actual object type.
  • 11. A first glance at the object form in the Heap • An object contains everything it inherits from each of its superclasses .That means that every object is also an instance of class Object so it can be treated that way. • If a reference is like a remote control, the remote control takes on more buttons as you move down the inheritance tree. So an Object reference has fewer buttons than the subtype reference “remote control”
  • 12. Casting an object reference back to its real type. If you are not sure of the class subtype you can use the instanceof operator to check. if (o instanceof Dog) { Dog d = (Dog) o; } • If you need to treat the object as its subtype you need a reference (remote control) to access all its specific methods. • You can make a new subtype reference to the object by copying the Object reference and forcing that copy to go into the subtype reference variable • The above procedure is called cast.
  • 13. Specifications changed. Is our design reusable? • Imagine that you have to use your previous design for a PetShop program. • You have to implement Pet behaviors like beFriendly() and play(). • You could simply add some methods more methods without breaking any existing method implementation. • But where would you implement the new methods and why? What are the possible problems that can occur? Let’s see look closer to some scenarios
  • 14. Put the new methods in the Superclass
  • 15. Override the methods in the subclasses’ implementation
  • 16. The methods go ONLY in the classes where they belong
  • 17. What the ideal approach would be?  A way to have pet behavior in just the pet classes  A way to guarantee that all pet classes have all of the same methods defined (same name, same arguments, same return types, no missing methods, etc.), without having to cross your fingers and hope all the programmers get it right.  A way to take advantage of polymorphism so that all pets can have their pet methods called, without having to use arguments, return types, and arrays for each and every pet class.
  • 18. The previous class diagram is not permitted • Multiple Inheritance is not supported in Java since it can lead to severe problems • The most serious is the so called Deadly Diamond of Death. So how do we handle the whole thing with Pet/Animal class?
  • 19. Interface gives us the solution • A Java interface solves multiple inheritance problem by giving the polymorphic benefits without the DDD. • The way that interfaces elect to side-step DDD is by keeping all the methods abstract. • That way the subclass that has to play that role must implement all the methods (provide body) SYNTAX To DEFINE an interface: public interface Pet {...} To IMPLEMENT an interface: public class Dog extends Canine implements Pet {...}
  • 20. Advantages and characteristics of an Interface • Interfaces buy us polymorphism and flexibility. • You can pass anything that implements an interface as an argument or a return type. • Even from a completely different inheritance tree • You treat an object by the role it plays and not the class that it was instantiated. • A class can implement multiple interfaces
  • 21. Things to think over when you design your class diagram How do you know whether to make a class, a subclass, an abstract class, or an interface? 1. Make a class that doesn’t extend anything(other than Object) when your new class doesn’t pass the IS-A test for any other type. Make a subclass (in other words, extend a class)only when you need to make a more specific version of a class and need to override or add new behaviors. 2. Use an abstract class when you want to define a template for a group of subclasses, and you have at least some implementation code that all subclasses could use. Make the class abstract when you want to guarantee that nobody can make objects of that type. 3. Use an interface when you want to define a role that other classes can play, regardless of where those classes are in the inheritance tree.