SlideShare a Scribd company logo
1 of 22
Sep 7, 2013
Abstract Classes and Interfaces
Java is “safer” than Python
 Python is very dynamic—classes and methods can be
added, modified, and deleted as the program runs
 If you have a call to a function that doesn't exist, Python will
give you a runtime error when you try to call it
 In Java, everything has to be defined before the program
begins to execute
 If you have a call to a function that doesn't exist, the compiler
marks it as a syntax error
 Syntax errors are far better than runtime errors

Among other things, they won’t make it into distributed code
 To achieve this, Java requires some additional kinds of classes
2
3
Abstract methods
 You can declare an object without defining it:
Person p;
 Similarly, you can declare a method without defining it:
public abstract void draw(int size);
 Notice that the body of the method is missing
 A method that has been declared but not defined is an
abstract method
4
Abstract classes I
 Any class containing an abstract method is an abstract
class
 You must declare the class with the keyword abstract:
abstract class MyClass {...}
 An abstract class is incomplete
 It has “missing” method bodies
 You cannot instantiate (create a new instance of) an
abstract class
5
Abstract classes II
 You can extend (subclass) an abstract class
 If the subclass defines all the inherited abstract methods, it
is “complete” and can be instantiated
 If the subclass does not define all the inherited abstract
methods, it too must be abstract
 You can declare a class to be abstract even if it does
not contain any abstract methods
 This prevents the class from being instantiated
6
Why have abstract classes?
 Suppose you wanted to create a class Shape, with
subclasses Oval, Rectangle, Triangle, Hexagon, etc.
 You don’t want to allow creation of a “Shape”
 Only particular shapes make sense, not generic ones
 If Shape is abstract, you can’t create a new Shape
 You can create a new Oval, a new Rectangle, etc.
 Abstract classes are good for defining a general
category containing specific, “concrete” classes
7
An example abstract class
 public abstract class Animal {
abstract int eat();
abstract void breathe();
}
 This class cannot be instantiated
 Any non-abstract subclass of Animal must provide the
eat() and breathe() methods
8
Why have abstract methods?
 Suppose you have a class Shape, but it isn’t abstract
 Shape should not have a draw() method
 Each subclass of Shape should have a draw() method
 Now suppose you have a variable Shape figure; where figure contains
some subclass object (such as a Star)
 It is a syntax error to say figure.draw(), because the Java compiler can’t tell
in advance what kind of value will be in the figure variable
 A class “knows” its superclass, but doesn’t know its subclasses
 An object knows its class, but a class doesn’t know its objects
 Solution: Give Shape an abstract method draw()
 Now the class Shape is abstract, so it can’t be instantiated
 The figure variable cannot contain a (generic) Shape, because it is impossible
to create one
 Any object (such as a Star object) that is a (kind of) Shape will have the
draw() method
 The Java compiler can depend on figure.draw() being a legal call and does
not give a syntax error
9
A problem
 class Shape { ... }
 class Star extends Shape {
void draw() { ... }
...
}
 class Crescent extends Shape {
void draw() { ... }
...
}
 Shape someShape = new Star();
 This is legal, because a Star is a Shape
 someShape.draw();
 This is a syntax error, because some Shape might not have a draw() method
 Remember: A class knows its superclass, but not its subclasses
10
A solution
 abstract class Shape {
abstract void draw();
}
 class Star extends Shape {
void draw() { ... }
...
}
 class Crescent extends Shape {
void draw() { ... }
...
}
 Shape someShape = new Star();
 This is legal, because a Star is a Shape
 However, Shape someShape = new Shape(); is no longer legal
 someShape.draw();
 This is legal, because every actual instance must have a draw() method
11
Interfaces
 An interface declares (describes) methods but does not supply
bodies for them
 interface KeyListener {
public void keyPressed(KeyEvent e);
public void keyReleased(KeyEvent e);
public void keyTyped(KeyEvent e);
}
 All the methods are implicitly public and abstract
 You can add these qualifiers if you like, but why bother?
 You cannot instantiate an interface
 An interface is like a very abstract class—none of its methods are
defined
 An interface may also contain constants (final variables)
12
Designing interfaces
 Most of the time, you will use Sun-supplied Java interfaces
 Sometimes you will want to design your own
 You would write an interface if you want classes of various types
to all have a certain set of capabilities
 For example, if you want to be able to create animated displays
of objects in a class, you might define an interface as:
 public interface Animatable {
install(Panel p);
display();
}
 Now you can write code that will display any Animatable class
in a Panel of your choice, simply by calling these methods
13
Implementing an interface I
 You extend a class, but you implement an interface
 A class can only extend (subclass) one other class, but it
can implement as many interfaces as you like
 Example:
class MyListener
implements KeyListener, ActionListener { … }
14
Implementing an interface II
 When you say a class implements an interface,
you are promising to define all the methods that
were declared in the interface
 Example:
class MyKeyListener implements KeyListener {
public void keyPressed(KeyEvent e) {...};
public void keyReleased(KeyEvent e) {...};
public void keyTyped(KeyEvent e) {...};
}
 The “...” indicates actual code that you must supply
 Now you can create a new MyKeyListener
15
Partially implementing an Interface
 It is possible to define some but not all of the methods
defined in an interface:
abstract class MyKeyListener implements KeyListener {
public void keyTyped(KeyEvent e) {...};
}
 Since this class does not supply all the methods it has
promised, it is an abstract class
 You must label it as such with the keyword abstract
 You can even extend an interface (to add methods):
 interface FunkyKeyListener extends KeyListener { ... }
16
What are interfaces for?
 Reason 1: A class can only extend one other class,
but it can implement multiple interfaces
 This lets the class fill multiple “roles”
 In writing Applets, it is common to have one class
implement several different listeners
 Example:
class MyApplet extends Applet
implements ActionListener, KeyListener {
...
}
 Reason 2: You can write methods that work for
more than one kind of class
17
How to use interfaces
 You can write methods that work with more than one class
 interface RuleSet { boolean isLegal(Move m, Board b);
void makeMove(Move m); }
 Every class that implements RuleSet must have these methods
 class CheckersRules implements RuleSet { // one implementation
public boolean isLegal(Move m, Board b) { ... }
public void makeMove(Move m) { ... }
}
 class ChessRules implements RuleSet { ... } // another implementation
 class LinesOfActionRules implements RuleSet { ... } // and another
 RuleSet rulesOfThisGame = new ChessRules();
 This assignment is legal because a rulesOfThisGame object is a RuleSet object
 if (rulesOfThisGame.isLegal(m, b)) { makeMove(m); }
 This statement is legal because, whatever kind of RuleSet object rulesOfThisGame
is, it must have isLegal and makeMove methods
18
instanceof
 instanceof is a keyword that tells you whether a variable
“is a” member of a class or interface
 For example, if
class Dog extends Animal implements Pet {...}
Animal fido = new Dog();
then the following are all true:
fido instanceof Dog
fido instanceof Animal
fido instanceof Pet
 instanceof is seldom used
 When you find yourself wanting to use instanceof, think about
whether the method you are writing should be moved to the individual
subclasses
19
Interfaces, again
 When you implement an interface, you promise to
define all the functions it declares
 There can be a lot of methods
interface KeyListener {
public void keyPressed(KeyEvent e);
public void keyReleased(KeyEvent e);
public void keyTyped(KeyEvent e);
}
 What if you only care about a couple of these
methods?
20
Adapter classes
 Solution: use an adapter class
 An adapter class implements an interface and provides
empty method bodies
class KeyAdapter implements KeyListener {
public void keyPressed(KeyEvent e) { };
public void keyReleased(KeyEvent e) { };
public void keyTyped(KeyEvent e) { };
}
 You can override only the methods you care about
 This isn’t elegant, but it does work
 Java provides a number of adapter classes
21
Vocabulary
 abstract method—a method which is declared but
not defined (it has no method body)
 abstract class—a class which either (1) contains
abstract methods, or (2) has been declared abstract
 instantiate—to create an instance (object) of a class
 interface—similar to a class, but contains only
abstract methods (and possibly constants)
 adapter class—a class that implements an interface
but has only empty method bodies
22
The End
Complexity has nothing to do with intelligence, simplicity
does.
— Larry Bossidy
Perfection is achieved, not when there is nothing more to
add, but when there is nothing left to take away.
— Antoine de Saint Exupery

More Related Content

What's hot

What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaEdureka!
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming conceptsGanesh Karthik
 
Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...
Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...
Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...Akhil Mittal
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#Abid Kohistani
 
Basics of reflection in java
Basics of reflection in javaBasics of reflection in java
Basics of reflection in javakim.mens
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Uzair Salman
 
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 InterfacesAhmed Nobi
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_typesAbed Bukhari
 
Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Javakim.mens
 
Chapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of JavaChapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of JavaAdan Hubahib
 
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 Singhdheeraj_cse
 

What's hot (20)

Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | Edureka
 
Java interface
Java interfaceJava interface
Java interface
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...
Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...
Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...
 
Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Basics of reflection in java
Basics of reflection in javaBasics of reflection in java
Basics of reflection in java
 
Java reflection
Java reflectionJava reflection
Java reflection
 
Chapter 12
Chapter 12Chapter 12
Chapter 12
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
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
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Java
 
Chapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of JavaChapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of Java
 
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
 
Java interface
Java interfaceJava interface
Java interface
 

Viewers also liked

Lecture on Java Concurrency Day 3 on Feb 11, 2009.
Lecture on Java Concurrency Day 3 on Feb 11, 2009.Lecture on Java Concurrency Day 3 on Feb 11, 2009.
Lecture on Java Concurrency Day 3 on Feb 11, 2009.Kyung Koo Yoon
 
Programming JVM Bytecode with Jitescript
Programming JVM Bytecode with JitescriptProgramming JVM Bytecode with Jitescript
Programming JVM Bytecode with JitescriptJoe Kutner
 
Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01Abhishek Khune
 
Multithreaded programming (as part of the the PTT lecture)
Multithreaded programming (as part of the the PTT lecture)Multithreaded programming (as part of the the PTT lecture)
Multithreaded programming (as part of the the PTT lecture)Ralf Laemmel
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 

Viewers also liked (14)

Threads
ThreadsThreads
Threads
 
Week0 introduction
Week0 introductionWeek0 introduction
Week0 introduction
 
Lecture on Java Concurrency Day 3 on Feb 11, 2009.
Lecture on Java Concurrency Day 3 on Feb 11, 2009.Lecture on Java Concurrency Day 3 on Feb 11, 2009.
Lecture on Java Concurrency Day 3 on Feb 11, 2009.
 
Binary trees
Binary treesBinary trees
Binary trees
 
Programming JVM Bytecode with Jitescript
Programming JVM Bytecode with JitescriptProgramming JVM Bytecode with Jitescript
Programming JVM Bytecode with Jitescript
 
Threads
ThreadsThreads
Threads
 
Sorting
SortingSorting
Sorting
 
Shared memory
Shared memoryShared memory
Shared memory
 
Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01
 
Multithreaded programming (as part of the the PTT lecture)
Multithreaded programming (as part of the the PTT lecture)Multithreaded programming (as part of the the PTT lecture)
Multithreaded programming (as part of the the PTT lecture)
 
07 java collection
07 java collection07 java collection
07 java collection
 
Java Notes
Java NotesJava Notes
Java Notes
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 

Similar to 06 abstract-classes

06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classesAnup Burange
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdfKp Sharma
 
Interfaces.ppt
Interfaces.pptInterfaces.ppt
Interfaces.pptVarunP31
 
Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Abou Bakr Ashraf
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)ssuser7f90ae
 
abstract,final,interface (1).pptx upload
abstract,final,interface (1).pptx uploadabstract,final,interface (1).pptx upload
abstract,final,interface (1).pptx uploaddashpayal697
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.pptrani marri
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceOUM SAOKOSAL
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examplesbindur87
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...yazad dumasia
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
Internet programming slide - java.ppt
Internet programming slide - java.pptInternet programming slide - java.ppt
Internet programming slide - java.pptMikeAdva
 

Similar to 06 abstract-classes (20)

06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdf
 
Interfaces .ppt
Interfaces .pptInterfaces .ppt
Interfaces .ppt
 
Interfaces.ppt
Interfaces.pptInterfaces.ppt
Interfaces.ppt
 
Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Visula C# Programming Lecture 8
Visula C# Programming Lecture 8
 
15 interfaces
15   interfaces15   interfaces
15 interfaces
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
 
Oop interfaces
Oop interfacesOop interfaces
Oop interfaces
 
abstract,final,interface (1).pptx upload
abstract,final,interface (1).pptx uploadabstract,final,interface (1).pptx upload
abstract,final,interface (1).pptx upload
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & Interface
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
Interface in java
Interface in javaInterface in java
Interface in java
 
4759826-Java-Thread
4759826-Java-Thread4759826-Java-Thread
4759826-Java-Thread
 
Java 06
Java 06Java 06
Java 06
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Internet programming slide - java.ppt
Internet programming slide - java.pptInternet programming slide - java.ppt
Internet programming slide - java.ppt
 

More from Abhishek Khune

More from Abhishek Khune (8)

Clanguage
ClanguageClanguage
Clanguage
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Applets
AppletsApplets
Applets
 
Clanguage
ClanguageClanguage
Clanguage
 
Java unit3
Java unit3Java unit3
Java unit3
 
Java unit2
Java unit2Java unit2
Java unit2
 
Linux introduction
Linux introductionLinux introduction
Linux introduction
 
Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)
 

Recently uploaded

Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 

Recently uploaded (20)

Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 

06 abstract-classes

  • 1. Sep 7, 2013 Abstract Classes and Interfaces
  • 2. Java is “safer” than Python  Python is very dynamic—classes and methods can be added, modified, and deleted as the program runs  If you have a call to a function that doesn't exist, Python will give you a runtime error when you try to call it  In Java, everything has to be defined before the program begins to execute  If you have a call to a function that doesn't exist, the compiler marks it as a syntax error  Syntax errors are far better than runtime errors  Among other things, they won’t make it into distributed code  To achieve this, Java requires some additional kinds of classes 2
  • 3. 3 Abstract methods  You can declare an object without defining it: Person p;  Similarly, you can declare a method without defining it: public abstract void draw(int size);  Notice that the body of the method is missing  A method that has been declared but not defined is an abstract method
  • 4. 4 Abstract classes I  Any class containing an abstract method is an abstract class  You must declare the class with the keyword abstract: abstract class MyClass {...}  An abstract class is incomplete  It has “missing” method bodies  You cannot instantiate (create a new instance of) an abstract class
  • 5. 5 Abstract classes II  You can extend (subclass) an abstract class  If the subclass defines all the inherited abstract methods, it is “complete” and can be instantiated  If the subclass does not define all the inherited abstract methods, it too must be abstract  You can declare a class to be abstract even if it does not contain any abstract methods  This prevents the class from being instantiated
  • 6. 6 Why have abstract classes?  Suppose you wanted to create a class Shape, with subclasses Oval, Rectangle, Triangle, Hexagon, etc.  You don’t want to allow creation of a “Shape”  Only particular shapes make sense, not generic ones  If Shape is abstract, you can’t create a new Shape  You can create a new Oval, a new Rectangle, etc.  Abstract classes are good for defining a general category containing specific, “concrete” classes
  • 7. 7 An example abstract class  public abstract class Animal { abstract int eat(); abstract void breathe(); }  This class cannot be instantiated  Any non-abstract subclass of Animal must provide the eat() and breathe() methods
  • 8. 8 Why have abstract methods?  Suppose you have a class Shape, but it isn’t abstract  Shape should not have a draw() method  Each subclass of Shape should have a draw() method  Now suppose you have a variable Shape figure; where figure contains some subclass object (such as a Star)  It is a syntax error to say figure.draw(), because the Java compiler can’t tell in advance what kind of value will be in the figure variable  A class “knows” its superclass, but doesn’t know its subclasses  An object knows its class, but a class doesn’t know its objects  Solution: Give Shape an abstract method draw()  Now the class Shape is abstract, so it can’t be instantiated  The figure variable cannot contain a (generic) Shape, because it is impossible to create one  Any object (such as a Star object) that is a (kind of) Shape will have the draw() method  The Java compiler can depend on figure.draw() being a legal call and does not give a syntax error
  • 9. 9 A problem  class Shape { ... }  class Star extends Shape { void draw() { ... } ... }  class Crescent extends Shape { void draw() { ... } ... }  Shape someShape = new Star();  This is legal, because a Star is a Shape  someShape.draw();  This is a syntax error, because some Shape might not have a draw() method  Remember: A class knows its superclass, but not its subclasses
  • 10. 10 A solution  abstract class Shape { abstract void draw(); }  class Star extends Shape { void draw() { ... } ... }  class Crescent extends Shape { void draw() { ... } ... }  Shape someShape = new Star();  This is legal, because a Star is a Shape  However, Shape someShape = new Shape(); is no longer legal  someShape.draw();  This is legal, because every actual instance must have a draw() method
  • 11. 11 Interfaces  An interface declares (describes) methods but does not supply bodies for them  interface KeyListener { public void keyPressed(KeyEvent e); public void keyReleased(KeyEvent e); public void keyTyped(KeyEvent e); }  All the methods are implicitly public and abstract  You can add these qualifiers if you like, but why bother?  You cannot instantiate an interface  An interface is like a very abstract class—none of its methods are defined  An interface may also contain constants (final variables)
  • 12. 12 Designing interfaces  Most of the time, you will use Sun-supplied Java interfaces  Sometimes you will want to design your own  You would write an interface if you want classes of various types to all have a certain set of capabilities  For example, if you want to be able to create animated displays of objects in a class, you might define an interface as:  public interface Animatable { install(Panel p); display(); }  Now you can write code that will display any Animatable class in a Panel of your choice, simply by calling these methods
  • 13. 13 Implementing an interface I  You extend a class, but you implement an interface  A class can only extend (subclass) one other class, but it can implement as many interfaces as you like  Example: class MyListener implements KeyListener, ActionListener { … }
  • 14. 14 Implementing an interface II  When you say a class implements an interface, you are promising to define all the methods that were declared in the interface  Example: class MyKeyListener implements KeyListener { public void keyPressed(KeyEvent e) {...}; public void keyReleased(KeyEvent e) {...}; public void keyTyped(KeyEvent e) {...}; }  The “...” indicates actual code that you must supply  Now you can create a new MyKeyListener
  • 15. 15 Partially implementing an Interface  It is possible to define some but not all of the methods defined in an interface: abstract class MyKeyListener implements KeyListener { public void keyTyped(KeyEvent e) {...}; }  Since this class does not supply all the methods it has promised, it is an abstract class  You must label it as such with the keyword abstract  You can even extend an interface (to add methods):  interface FunkyKeyListener extends KeyListener { ... }
  • 16. 16 What are interfaces for?  Reason 1: A class can only extend one other class, but it can implement multiple interfaces  This lets the class fill multiple “roles”  In writing Applets, it is common to have one class implement several different listeners  Example: class MyApplet extends Applet implements ActionListener, KeyListener { ... }  Reason 2: You can write methods that work for more than one kind of class
  • 17. 17 How to use interfaces  You can write methods that work with more than one class  interface RuleSet { boolean isLegal(Move m, Board b); void makeMove(Move m); }  Every class that implements RuleSet must have these methods  class CheckersRules implements RuleSet { // one implementation public boolean isLegal(Move m, Board b) { ... } public void makeMove(Move m) { ... } }  class ChessRules implements RuleSet { ... } // another implementation  class LinesOfActionRules implements RuleSet { ... } // and another  RuleSet rulesOfThisGame = new ChessRules();  This assignment is legal because a rulesOfThisGame object is a RuleSet object  if (rulesOfThisGame.isLegal(m, b)) { makeMove(m); }  This statement is legal because, whatever kind of RuleSet object rulesOfThisGame is, it must have isLegal and makeMove methods
  • 18. 18 instanceof  instanceof is a keyword that tells you whether a variable “is a” member of a class or interface  For example, if class Dog extends Animal implements Pet {...} Animal fido = new Dog(); then the following are all true: fido instanceof Dog fido instanceof Animal fido instanceof Pet  instanceof is seldom used  When you find yourself wanting to use instanceof, think about whether the method you are writing should be moved to the individual subclasses
  • 19. 19 Interfaces, again  When you implement an interface, you promise to define all the functions it declares  There can be a lot of methods interface KeyListener { public void keyPressed(KeyEvent e); public void keyReleased(KeyEvent e); public void keyTyped(KeyEvent e); }  What if you only care about a couple of these methods?
  • 20. 20 Adapter classes  Solution: use an adapter class  An adapter class implements an interface and provides empty method bodies class KeyAdapter implements KeyListener { public void keyPressed(KeyEvent e) { }; public void keyReleased(KeyEvent e) { }; public void keyTyped(KeyEvent e) { }; }  You can override only the methods you care about  This isn’t elegant, but it does work  Java provides a number of adapter classes
  • 21. 21 Vocabulary  abstract method—a method which is declared but not defined (it has no method body)  abstract class—a class which either (1) contains abstract methods, or (2) has been declared abstract  instantiate—to create an instance (object) of a class  interface—similar to a class, but contains only abstract methods (and possibly constants)  adapter class—a class that implements an interface but has only empty method bodies
  • 22. 22 The End Complexity has nothing to do with intelligence, simplicity does. — Larry Bossidy Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away. — Antoine de Saint Exupery