SlideShare ist ein Scribd-Unternehmen logo
1 von 47
Abstract Classes and Interfaces
The objectives of this chapter are:
To explore the concept of abstract classes
To understand interfaces
To understand the importance of both.
What is an Abstract class?
Superclasses are created through the process called
"generalization"
Common features (methods or variables) are factored out of object
classifications (ie. classes).
Those features are formalized in a class. This becomes the superclass
The classes from which the common features were taken become
subclasses to the newly created super class

Often, the superclass does not have a "meaning" or does not
directly relate to a "thing" in the real world
It is an artifact of the generalization process
Because of this, abstract classes cannot be instantiated
They act as place holders for abstraction
Abstract Class Example
In the following example, the subclasses represent objects
taken from the problem domain.
The superclass represents an abstract concept that does not
exist "as is" in the real world.

Abstract superclass:

Vehicle
- make: String
- model: String
- tireCount: int

Car
- trunkCapacity: int

Note: UML represents abstract
classes by displaying their name
in italics.

Truck
- bedCapacity: int
Be careful not to over use abstract classes
Every abstract class increases the complexity of your
design
Every subclass increases the complexity of your design
Ensure that you receive acceptable return in terms of functionality given
the added complexity.
Defining Abstract Classes
Inheritance is declared using the "extends" keyword
If inheritance is not defined, the class extends a class called Object
public abstract class Vehicle
{
private String make;
private String model;
private int tireCount;
[...]

public class Car extends Vehicle
{
private int trunkCapacity;
[...]

public class Truck extends Vehicle
{
private int bedCapacity;
[...]

Vehicle
- make: String
- model: String
- tireCount: int

Car
- trunkCapacity: int

Truck
- bedCapacity: int

Often referred to as "concrete" classes
Abstract Methods
Methods can also be abstracted
An abstract method is one to which a signature has been provided, but
no implementation for that method is given.
An Abstract method is a placeholder. It means that we declare that a
method must exist, but there is no meaningful implementation for that
methods within this class

Any class which contains an abstract method MUST also be
abstract
Any class which has an incomplete method definition cannot
be instantiated (ie. it is abstract)
Abstract classes can contain both concrete and abstract
methods.
If a method can be implemented within an abstract class, and
implementation should be provided.
Abstract Method Example
In the following example, a Transaction's value can be
computed, but there is no meaningful implementation that can
be defined within the Transaction class.
How a transaction is computed is dependent on the transaction's type
Note: This is polymorphism.

Transaction
- computeValue(): int

RetailSale
- computeValue(): int

StockTrade
- computeValue(): int
Defining Abstract Methods
Inheritance is declared using the "extends" keyword
If inheritance is not defined, the class extends a class called Object
Note: no implementation
public abstract class Transaction
{
public abstract int computeValue();

Transaction
- computeValue(): int

public class RetailSale extends Transaction
{
RetailSale
public int computeValue()
- computeValue(): int
{
[...]
public class StockTrade extends Transaction
{
public int computeValue()
{
[...]

StockTrade
- computeValue(): int
What is an Interface?
An interface is similar to an abstract class with the following
exceptions:
All methods defined in an interface are abstract. Interfaces can contain
no implementation
Interfaces cannot contain instance variables. However, they can
contain public static final variables (ie. constant class variables)
•

Interfaces are declared using the "interface" keyword
If an interface is public, it must be contained in a file which
has the same name.

•

Interfaces are more abstract than abstract classes

•

Interfaces are implemented by classes using the
"implements" keyword.
Declaring an Interface
In Steerable.java:
public interface Steerable
{
public void turnLeft(int degrees);
public void turnRight(int degrees);
}

In Car.java:

When a class "implements" an
interface, the compiler ensures that
it provides an implementation for
all methods defined within the
interface.

public class Car extends Vehicle implements Steerable
{
public int turnLeft(int degrees)
{
[...]
}
public int turnRight(int degrees)
{
[...]
}
Implementing Interfaces
A Class can only inherit from one superclass. However, a
class may implement several Interfaces
The interfaces that a class implements are separated by commas
•

Any class which implements an interface must provide an
implementation for all methods defined within the interface.
NOTE: if an abstract class implements an interface, it NEED NOT
implement all methods defined in the interface. HOWEVER, each
concrete subclass MUST implement the methods defined in the
interface.

•

Interfaces can inherit method signatures from other
interfaces.
Declaring an Interface
In Car.java:
public class Car extends Vehicle implements Steerable, Driveable
{
public int turnLeft(int degrees)
{
[...]
}
public int turnRight(int degrees)
{
[...]
}
// implement methods defined within the Driveable interface
Inheriting Interfaces
If a superclass implements an interface, it's subclasses also
implement the interface
public abstract class Vehicle implements Steerable
{
private String make;
[...]

public class Car extends Vehicle
{
private int trunkCapacity;
[...]

public class Truck extends Vehicle
{
private int bedCapacity;
[...]

Vehicle
- make: String
- model: String
- tireCount: int

Car
- trunkCapacity: int

Truck
- bedCapacity: int
Multiple Inheritance?
Some people (and textbooks) have said that allowing classes
to implement multiple interfaces is the same thing as multiple
inheritance
This is NOT true. When you implement an interface:
The implementing class does not inherit instance variables
The implementing class does not inherit methods (none are defined)
The Implementing class does not inherit associations

Implementation of interfaces is not inheritance. An interface
defines a list of methods which must be implemented.
Interfaces as Types
When a class is defined, the compiler views the class as a
new type.
The same thing is true of interfaces. The compiler regards an
interface as a type.
It can be used to declare variables or method parameters
int i;
Car myFleet[];
Steerable anotherFleet[];
[...]
myFleet[i].start();
anotherFleet[i].turnLeft(100);
anotherFleet[i+1].turnRight(45);
Abstract Classes Versus Interfaces
When should one use an Abstract class instead of an
interface?
If the subclass-superclass relationship is genuinely an "is a"
relationship.
If the abstract class can provide an implementation at the appropriate
level of abstraction
•

When should one use an interface in place of an Abstract
Class?
When the methods defined represent a small portion of a class
When the subclass needs to inherit from another class
When you cannot reasonably implement any of the methods
Difference Between Interface and
Abstract Class


Main difference is methods of a Java interface are
implicitly abstract and cannot have
implementations. A Java abstract class can
have instance methods that implements a default
behavior.
Difference Between Interface and
Abstract Class


Variables declared in a Java interface is by
default final. An abstract class may contain nonfinal variables.
Difference Between Interface and
Abstract Class


Members of a Java interface are public by default.
A Java abstract class can have the usual flavors of
class members like private, protected, etc..
Difference Between Interface and
Abstract Class


Java interface should be implemented using
keyword “implements”; A Java abstract class
should be extended using keyword “extends”.
Difference Between Interface and
Abstract Class


An interface can extend another Java interface
only, an abstract class can extend another Java
class and implement multiple Java interfaces.
Difference Between Interface and
Abstract Class


A Java class can implement multiple interfaces but
it can extend only one abstract class.



Interface is absolutely abstract and cannot
be instantiated; A Java abstract class also cannot be
instantiated, but can be invoked if a main() exists.
Difference Between Interface and
Abstract Class


In comparison with java abstract classes, java
interfaces are slow as it requires extra indirection.
A fact about Interfaces


A Java class may implement, and an interface may
extend, any number of interfaces; however an
interface may not implement an interface.
Abstract Classes and Interfaces
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
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
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
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”



if Shape is abstract, you can’t create a new Shape




only particular shapes make sense, not generic ones
you can create a new Oval, a new Rectangle, etc.

abstract classes are good for defining a general
category containing specific, “concrete” classes
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
why have abstract methods?



suppose you have a class Shape that 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

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
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
a solution








abstract class Shape {
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
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 cannot instantiate an interface




you can add these qualifiers if you like, but why bother?

an interface is like a very abstract class—none of its methods are defined

an interface may also contain constants (final variables)
“constants”


a constant is a variable, or field, that is marked
final
public final int SPRING = 0;
public final int SUMMER = 1;
public final int FALL = 2;
public final int WINTER = 3;



its value cannot be changed at runtime



its name should, by convention, be all caps
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
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
{…}
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
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
{ ... }
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
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 method is legal because, whatever kind of RuleSet object rulesOfThisGame is, it must have isLegal and
makeMove methods
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
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?
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
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
the end

Weitere ähnliche Inhalte

Was ist angesagt?

Chapter 9 Abstract Class
Chapter 9 Abstract ClassChapter 9 Abstract Class
Chapter 9 Abstract ClassOUM SAOKOSAL
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in javaHitesh Kumar
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAsivasundari6
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methodsShubham Dwivedi
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packagesVINOTH R
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Abstract Class Presentation
Abstract Class PresentationAbstract Class Presentation
Abstract Class Presentationtigerwarn
 
Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java Ravi_Kant_Sahu
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)Ritika Sharma
 
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
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classesAKANSH SINGHAL
 
Java string handling
Java string handlingJava string handling
Java string handlingSalman Khan
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Introduction to method overloading & method overriding in java hdm
Introduction to method overloading & method overriding  in java  hdmIntroduction to method overloading & method overriding  in java  hdm
Introduction to method overloading & method overriding in java hdmHarshal Misalkar
 

Was ist angesagt? (20)

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Chapter 9 Abstract Class
Chapter 9 Abstract ClassChapter 9 Abstract Class
Chapter 9 Abstract Class
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVA
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Abstract class
Abstract classAbstract class
Abstract class
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Abstract Class Presentation
Abstract Class PresentationAbstract Class Presentation
Abstract Class Presentation
 
Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
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
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classes
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Introduction to method overloading & method overriding in java hdm
Introduction to method overloading & method overriding  in java  hdmIntroduction to method overloading & method overriding  in java  hdm
Introduction to method overloading & method overriding in java hdm
 
Generics C#
Generics C#Generics C#
Generics C#
 
Java constructors
Java constructorsJava constructors
Java constructors
 

Ähnlich wie Java interfaces & abstract classes

Abstract class
Abstract classAbstract class
Abstract classFraboni Ec
 
Abstract class
Abstract classAbstract class
Abstract classJames Wong
 
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
 
Interfaces.ppt
Interfaces.pptInterfaces.ppt
Interfaces.pptVarunP31
 
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 InterfacesJamsher bhanbhro
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdfSudhanshiBakre1
 
06_OOVP.pptx object oriented and visual programming
06_OOVP.pptx object oriented and visual programming06_OOVP.pptx object oriented and visual programming
06_OOVP.pptx object oriented and visual programmingdeffa5
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 eehomeworkping9
 
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
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10Terry Yoast
 

Ähnlich wie Java interfaces & abstract classes (20)

Abstract class
Abstract classAbstract class
Abstract class
 
Abstract class
Abstract classAbstract class
Abstract class
 
Abstract class
Abstract classAbstract class
Abstract class
 
Abstract class
Abstract classAbstract class
Abstract class
 
Abstract class
Abstract classAbstract class
Abstract class
 
Abstract class
Abstract classAbstract class
Abstract class
 
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
 
Interfaces .ppt
Interfaces .pptInterfaces .ppt
Interfaces .ppt
 
Interfaces.ppt
Interfaces.pptInterfaces.ppt
Interfaces.ppt
 
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
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
15 interfaces
15   interfaces15   interfaces
15 interfaces
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdf
 
Oop
OopOop
Oop
 
Java basics
Java basicsJava basics
Java basics
 
06_OOVP.pptx object oriented and visual programming
06_OOVP.pptx object oriented and visual programming06_OOVP.pptx object oriented and visual programming
06_OOVP.pptx object oriented and visual programming
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 ee
 
C# program structure
C# program structureC# program structure
C# program structure
 
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
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 

Mehr von Shreyans Pathak

Mehr von Shreyans Pathak (7)

Introduction to 8086 microprocessor
Introduction to 8086 microprocessorIntroduction to 8086 microprocessor
Introduction to 8086 microprocessor
 
8051 interrupts
8051 interrupts8051 interrupts
8051 interrupts
 
8051 Timers and Counters
8051 Timers and Counters8051 Timers and Counters
8051 Timers and Counters
 
AVL Trees
AVL TreesAVL Trees
AVL Trees
 
8051 Programming Instruction Set
 8051 Programming Instruction Set 8051 Programming Instruction Set
8051 Programming Instruction Set
 
Introduction state machine
Introduction state machineIntroduction state machine
Introduction state machine
 
Java packages
Java packagesJava packages
Java packages
 

Kürzlich hochgeladen

Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
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
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
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
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
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
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
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
 

Kürzlich hochgeladen (20)

Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
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
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
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
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
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
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).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Ữ Â...
 

Java interfaces & abstract classes

  • 1. Abstract Classes and Interfaces The objectives of this chapter are: To explore the concept of abstract classes To understand interfaces To understand the importance of both.
  • 2. What is an Abstract class? Superclasses are created through the process called "generalization" Common features (methods or variables) are factored out of object classifications (ie. classes). Those features are formalized in a class. This becomes the superclass The classes from which the common features were taken become subclasses to the newly created super class Often, the superclass does not have a "meaning" or does not directly relate to a "thing" in the real world It is an artifact of the generalization process Because of this, abstract classes cannot be instantiated They act as place holders for abstraction
  • 3. Abstract Class Example In the following example, the subclasses represent objects taken from the problem domain. The superclass represents an abstract concept that does not exist "as is" in the real world. Abstract superclass: Vehicle - make: String - model: String - tireCount: int Car - trunkCapacity: int Note: UML represents abstract classes by displaying their name in italics. Truck - bedCapacity: int
  • 4. Be careful not to over use abstract classes Every abstract class increases the complexity of your design Every subclass increases the complexity of your design Ensure that you receive acceptable return in terms of functionality given the added complexity.
  • 5. Defining Abstract Classes Inheritance is declared using the "extends" keyword If inheritance is not defined, the class extends a class called Object public abstract class Vehicle { private String make; private String model; private int tireCount; [...] public class Car extends Vehicle { private int trunkCapacity; [...] public class Truck extends Vehicle { private int bedCapacity; [...] Vehicle - make: String - model: String - tireCount: int Car - trunkCapacity: int Truck - bedCapacity: int Often referred to as "concrete" classes
  • 6. Abstract Methods Methods can also be abstracted An abstract method is one to which a signature has been provided, but no implementation for that method is given. An Abstract method is a placeholder. It means that we declare that a method must exist, but there is no meaningful implementation for that methods within this class Any class which contains an abstract method MUST also be abstract Any class which has an incomplete method definition cannot be instantiated (ie. it is abstract) Abstract classes can contain both concrete and abstract methods. If a method can be implemented within an abstract class, and implementation should be provided.
  • 7. Abstract Method Example In the following example, a Transaction's value can be computed, but there is no meaningful implementation that can be defined within the Transaction class. How a transaction is computed is dependent on the transaction's type Note: This is polymorphism. Transaction - computeValue(): int RetailSale - computeValue(): int StockTrade - computeValue(): int
  • 8. Defining Abstract Methods Inheritance is declared using the "extends" keyword If inheritance is not defined, the class extends a class called Object Note: no implementation public abstract class Transaction { public abstract int computeValue(); Transaction - computeValue(): int public class RetailSale extends Transaction { RetailSale public int computeValue() - computeValue(): int { [...] public class StockTrade extends Transaction { public int computeValue() { [...] StockTrade - computeValue(): int
  • 9. What is an Interface? An interface is similar to an abstract class with the following exceptions: All methods defined in an interface are abstract. Interfaces can contain no implementation Interfaces cannot contain instance variables. However, they can contain public static final variables (ie. constant class variables) • Interfaces are declared using the "interface" keyword If an interface is public, it must be contained in a file which has the same name. • Interfaces are more abstract than abstract classes • Interfaces are implemented by classes using the "implements" keyword.
  • 10. Declaring an Interface In Steerable.java: public interface Steerable { public void turnLeft(int degrees); public void turnRight(int degrees); } In Car.java: When a class "implements" an interface, the compiler ensures that it provides an implementation for all methods defined within the interface. public class Car extends Vehicle implements Steerable { public int turnLeft(int degrees) { [...] } public int turnRight(int degrees) { [...] }
  • 11. Implementing Interfaces A Class can only inherit from one superclass. However, a class may implement several Interfaces The interfaces that a class implements are separated by commas • Any class which implements an interface must provide an implementation for all methods defined within the interface. NOTE: if an abstract class implements an interface, it NEED NOT implement all methods defined in the interface. HOWEVER, each concrete subclass MUST implement the methods defined in the interface. • Interfaces can inherit method signatures from other interfaces.
  • 12. Declaring an Interface In Car.java: public class Car extends Vehicle implements Steerable, Driveable { public int turnLeft(int degrees) { [...] } public int turnRight(int degrees) { [...] } // implement methods defined within the Driveable interface
  • 13. Inheriting Interfaces If a superclass implements an interface, it's subclasses also implement the interface public abstract class Vehicle implements Steerable { private String make; [...] public class Car extends Vehicle { private int trunkCapacity; [...] public class Truck extends Vehicle { private int bedCapacity; [...] Vehicle - make: String - model: String - tireCount: int Car - trunkCapacity: int Truck - bedCapacity: int
  • 14. Multiple Inheritance? Some people (and textbooks) have said that allowing classes to implement multiple interfaces is the same thing as multiple inheritance This is NOT true. When you implement an interface: The implementing class does not inherit instance variables The implementing class does not inherit methods (none are defined) The Implementing class does not inherit associations Implementation of interfaces is not inheritance. An interface defines a list of methods which must be implemented.
  • 15. Interfaces as Types When a class is defined, the compiler views the class as a new type. The same thing is true of interfaces. The compiler regards an interface as a type. It can be used to declare variables or method parameters int i; Car myFleet[]; Steerable anotherFleet[]; [...] myFleet[i].start(); anotherFleet[i].turnLeft(100); anotherFleet[i+1].turnRight(45);
  • 16. Abstract Classes Versus Interfaces When should one use an Abstract class instead of an interface? If the subclass-superclass relationship is genuinely an "is a" relationship. If the abstract class can provide an implementation at the appropriate level of abstraction • When should one use an interface in place of an Abstract Class? When the methods defined represent a small portion of a class When the subclass needs to inherit from another class When you cannot reasonably implement any of the methods
  • 17. Difference Between Interface and Abstract Class  Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior.
  • 18. Difference Between Interface and Abstract Class  Variables declared in a Java interface is by default final. An abstract class may contain nonfinal variables.
  • 19. Difference Between Interface and Abstract Class  Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
  • 20. Difference Between Interface and Abstract Class  Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.
  • 21. Difference Between Interface and Abstract Class  An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
  • 22. Difference Between Interface and Abstract Class  A Java class can implement multiple interfaces but it can extend only one abstract class.  Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
  • 23. Difference Between Interface and Abstract Class  In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.
  • 24. A fact about Interfaces  A Java class may implement, and an interface may extend, any number of interfaces; however an interface may not implement an interface.
  • 25.
  • 26. Abstract Classes and Interfaces
  • 27. 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
  • 28. 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
  • 29. 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
  • 30. 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”   if Shape is abstract, you can’t create a new Shape   only particular shapes make sense, not generic ones you can create a new Oval, a new Rectangle, etc. abstract classes are good for defining a general category containing specific, “concrete” classes
  • 31. 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
  • 32. why have abstract methods?  suppose you have a class Shape that 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 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
  • 33. 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
  • 34. a solution     abstract class Shape { 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
  • 35. 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 cannot instantiate an interface   you can add these qualifiers if you like, but why bother? an interface is like a very abstract class—none of its methods are defined an interface may also contain constants (final variables)
  • 36. “constants”  a constant is a variable, or field, that is marked final public final int SPRING = 0; public final int SUMMER = 1; public final int FALL = 2; public final int WINTER = 3;  its value cannot be changed at runtime  its name should, by convention, be all caps
  • 37. 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
  • 38. 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 {…}
  • 39. 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
  • 40. 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 { ... }
  • 41. 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
  • 42. 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 method is legal because, whatever kind of RuleSet object rulesOfThisGame is, it must have isLegal and makeMove methods
  • 43. 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
  • 44. 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?
  • 45. 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
  • 46. 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