SlideShare a Scribd company logo
Compiled By: Umm-e-Laila
Lecture # 9
1
Interfaces in Java
Course Books
◼ Text Book:
◼ Herbert Schildt, Java: The Complete Reference, McGraw-Hill
Education, Eleventh Edition
◼ Craig Larman, Applying UML & patterns, 2 edition
◼ Reference Books:
◼ Cay S. Horstmann, Big Java: Early Objects, Wiley, 7th Edition
◼ Herbert Schildt, Java: A Beginner's Guide, McGraw-Hill Education,
Eighth Edition
2
Course Instructors
◼ Umm-e-Laila ulaila@ssuet.edu.pk
Assistant Professor, CED
Room Number: BS-04
Tel: 111-994-994, Ext. 536
◼ Aneeta Siddiqui aarshad@ssuet.edu.pk
Assistant Professor, CED
Room Number: BS-03
Tel: 111-994-994,
Course Website
◼ http://sites.google.com/site/ulaila206
4
What is an Interface
◼ In Java, only single inheritance is permitted. However,
Java provides a construct called an interface which can
be implemented by a class.
◼ An interface defines a protocol of behavior that can be
implemented by any class anywhere in the class
hierarchy.
◼ Interfaces are similar to abstract classes but with some
differences
◼ A class can implement any number of interfaces. In
effect using interfaces gives us the benefit of multiple
inheritance without many of it’s problems.
◼ Interfaces are compiled into bytecode just like classes.
◼ Interfaces cannot be instantiated.
◼ Can use interface as a data type for variables.
◼ Can also use an interface as the result of a cast
What is an Interface cont..
◼ Interfaces can contain only abstract methods and
constants.
◼ An interface defines a set of methods but does not
implement them. A class that implements the interface
agrees to implement all the methods defined in the
interface, thereby agreeing to certain behavior.
◼ An interface is a named collection of method definitions
(without implementations).
◼ Interface reserve behaviors for classes that implement
them.
6
What is an Interface cont..
◼ Methods declared in an interface are always public and
abstract, therefore Java compiler will not complain if you
omit both keywords
◼ Static methods cannot be declared in the interfaces –
these methods are never abstract and do not express
behavior of objects
◼ Variables can be declared in the interfaces. They can
only be declared as static and final. – Both keyword are
assumed by default and can be safely omitted.
◼ Sometimes interfaces declare only constants – be used
to effectively import sets of related constants
7
Defining an Interface
◼ Defining an interface is similar to creating a new class.
◼ An interface definition has two components: the interface
declaration and the interface body.
interface Declaration
{
interfaceBody
}
◼ The interfaceDeclaration declares various attributes
about the interface such as its name and whether it
extends another interface.
◼ The interfaceBody contains the constant and method
declarations within the interface
8
Interface
public interface StockWatcher
{
final String sunTicker = "SUNW";
final String oracleTicker = "ORCL";
final String ciscoTicker = "CSCO";
void valueChanged(String tickerSymbol, double newValue);
}
◼ If you do not specify that your interface is public,
your interface will be accessible only to classes that are
defined in the same package as the interface
9
Implementing an Interface
◼ Include an implements clause in the class
declaration.
◼ A class can implement more than one interface
(the Java platform supports multiple inheritance
for interfaces), so the implements keyword is
followed by a comma-separated list of the
interfaces implemented by the class.
◼ When implement an interface, either the class
must implement all the methods declared in the
interface and its superinterfaces, or the class
must be declared abstract
10
Implementation of Interface syntax
public class StockMonitor implements StockWatcher
{ public void valueChanged(String tickerSymbol,double newValue)
{
if (tickerSymbol.equals(sunTicker))
{ ... }
else if
(tickerSymbol.equals(oracleTicker))
{ ... }
else if
(tickerSymbol.equals(ciscoTicker))
{ ... }
}
}
Properties of Interface
◼ A new interface is a new reference data type.
◼ Interfaces are not instantiated with new, but
they have certain properties similar to
ordinary classes
◼ You can declare that an object variable will be
of that interface type
e.g.
Comparable x = new Tile(…);
Tile y = new Tile(…);
if (x.compareTo(y) < 0) …
12
Super Interface(Extends Interface)
◼ An interface can extend other interfaces, just as
a class can extend or subclass another class.
◼ An interface can extend any number of
interfaces.
◼ The list of superinterfaces is a comma-separated
list of all the interfaces extended by the new
interface
modifier interface interfaceID extends
comma-delimited-list-of-interfaces
{
//constants/method signatures
}
13
Super Interface(cont)
◼ Obviously, any class which implements a
“sub-interface” will have to implement
each of the methods contained in it’s
“super-interfaces”
◼ Two ways of extending interfaces:
❑ Add new methods
❑ Define new constants
◼ Interfaces do not have a single top-level
interface. (Like Object class for classes)
14
Interface vs. abstract class
Interface Abstract class
Fields Only constants.
By default final
Constants and variable
data(may contain non
final variable)
Methods No implementation
allowed (no abstract
modifier necessary)
Abstract or concrete
Accessibility Members of a java
interface are public by
default
A member of an
abstract class can
either be private,
protective or public.
Interface vs. abstract class (cont)
Interface Abstract class
Inheritance A subclass can
implement many
interfaces
A subclass can
inherit only one
class
Can extend
numerous
interfaces
Can implement
numerous
interfaces
Cannot extend a
class
Extends one class
Interface vs. abstract class (cont)
Interface Abstract class
Root none Object (of all
classes)
names Adjective or Nouns Nouns
Interface Example
◼ First Interface standard Remote
interface stdremote{
int volume limit=500;
public abstract void volume();
void setChannel();
void brightness();
void mute();
}
18
◼ Second Interface ExtendedRemote
interface extends ExtRemote{
void autoconfiguration();
void doubly();
void AVL();
}
◼ Third Interface ModernRemote using
StdRemote and ExtRemote
interface ModernRemote extends
StdRemote,ExtRemote {}
19
◼ Abstract Class Tv
abstract class Tv{
abstract void Switch on();
abstract void Switch off();
}
◼ Provide Implementation for the given class
also show difference if any
◼ Class Sony extends TV implements
ModernRemote{}
◼ Class Sony extends TV implements StdRemote,
ExtRemote{ }
20
21
Interface - Example
VOLUME_LIMIT=500 :int
Volume():void
Mute():void
Brightness():void
setChannels(): void
<<Interface>>
StdRemote
<<Interface>>
ExtendedRemote
AVL():void
NetFlix():void
PrimeVdo():void
autoConfiguration(): void
<<Interface>>
ModernRemotec
22
Interface - Example
<<abstract>>
TV
abstract SwitchOn():void
abstract SwitchOff():void
<<Interface>>
ModernRemote
<<class>
SonyTv
Example 2
◼ First Interface BiCycle
public interface BiCycle {
void Speed(int a);
void ApplyBrake(int a);
void ChangeGear(int a);}
23
Example 2
◼ Class MyBiCycle
public class MyBiCycle implements BiCycle {
double speed;
int gear;
public MyBiCycle(double speed, int gear) {
this.speed = speed; this.gear = gear;
}
public void Speed(int a){
speed+=a; }
public void ApplyBrake(int a){
speed-=a; }
public void ChangeGear(int a){
gear=a; }
public String toString(){ return "BiCycle
Speed="+speed+"n BiCycle is on Gear"+gear; } }
24
Example 2
◼ Test Class
public class TestMyBiCycle {
public static void main(String[]
args) { BiCycle bi; bi=new
MyBiCycle(50,2);
System.out.println(""+bi); }
}
Output:
BiCycle Speed=50.0
BiCycle is on Gear2
25
Interfaces Cannot Grow!
◼ Add some functionality to StockWatcher?
public interface StockWatcher
{
final String sunTicker = "SUNW";
final String oracleTicker = "ORCL";
final String ciscoTicker = "CSCO";
void valueChanged(String tickerSymbol,
double newValue);
void currentValue(String tickerSymbol,
double newValue);
}
◼ If you make this change, all classes that implement the old interface
will break because they don’t implement the interface anymore!
26
Default Method in Java Interface( 1.8 version)
◼ If we want to add cadenceRate (or pedaling rate) method
in the interface BiCycle . it will break MyBike class
therefore java 1.8 provides a default method
implementation to avoid this problem. otherwise
MyBiCycle need to make changes in it
◼ First Interface BiCycle
public interface BiCycle {
void Speed(int a);
void ApplyBrake(int a);
void ChangeGear(int a);
void CadenceRate(int a);
}
27
1:Create default method in Interface BiCycle
public interface BiCycle {
void Speed(int a);
void ApplyBrake(int a);
void ChangeGear(int a);
default void CadenceRate(int a){
System.out.println(“Cadence is 120”);
} }}
28
2:Create Test Class to show usage of default
method
public class TestMyBiCycle {
public static void main(String[] args) {
BiCycle bi;
bi=new MyBiCycle(50,2);
System.out.println(""+bi);
bi.CadenceRate(2);
}}
output:
BiCycle Speed=50.0
BiCycle is on Gear2
Cadence is 120
29
3:Implements Cadence in Class MyBiCycle
public class MyBiCycle implements BiCycle {
double speed;
int gear;
double cadence;
public MyBiCycle(double speed, int gear, double cadence) {
this.speed = speed;
this.gear = gear;
this.cadence=cadence; }
public void Speed(int a){
speed+=a; }
public void ApplyBrake(int a){
speed-=a;
}
public void ChangeGear(int a){
gear=a; }
public String toString(){
return "BiCycle Speed="+speed+"n BiCycle is on Gear"+gear;+ "n
with cadence rate"+cadence;}
public void CadenceRate(int a){
cadence+=a;
}
30
4: Test class for default method
public class TestMyBiCycle {
public static void main(String[] args) {
BiCycle bi;
bi=new MyBiCycle(50,2,10);
System.out.println(""+bi);
bi.CadenceRate(2);
System.out.println(""+bi); } }
Output:
BiCycle Speed=50.0
BiCycle is on Gear2 with cadence rate10.0
BiCycle Speed=50.0
BiCycle is on Gear2 with cadence rate12.0
31
32
Interface - Example
speak()
Politician Priest
<<Interface>>
Speaker
speak() speak()
Lecturer
speak()
33
Implementing Interfaces Example
class Politician implements Speaker {
public void speak(){
System.out.println(“Talk politics”);
}
}
class Priest implements Speaker {
public void speak(){
System.out.println(“Religious Talks”);
}
}
class Lecturer implements Speaker {
public void speak(){
System.out.println(“Talks Object Oriented Design and Programming!”);
}
}
34
Student Assessment Example
◼ Consider a university where students who participate in
the national games or Olympics are given some grace
marks. Therefore, the final marks awarded =
Exam_Marks + Sports_Grace_Marks. A class diagram
representing this scenario is as follow:
Student Sports
Exam
Results
extends
extends
implements
35
Software Implementation
class Student
{
// student no and access methods
}
interface Sport
{
// sports grace marks (say 5 marks) and abstract methods
}
class Exam extends Student
{
// example marks (test1 and test 2 marks) and access methods
}
class Results extends Exam implements Sport
{
// implementation of abstract methods of Sport interface
// other methods to compute total marks = test1+test2+sports_grace_marks;
// other display or final results access methods
}
Summary
◼ An abstract method has no method body.
An abstract class contains abstract
methods.
◼ An interface is a collection of abstract
methods and constants. A class
implements an interface by declaring it in
its implements clause, and providing a
method body for each abstract method.
36

More Related Content

PPTX
Lecture 18
PPT
Java interface
PPT
Interface in java By Dheeraj Kumar Singh
PPTX
OOFeatures_revised-2.pptx
PPT
Java interfaces
PDF
‏‏‏‏‏‏oop lecture 6_١٢٥٩٤٧taiz univercity.pdf
PDF
21UCAC31 Java Programming.pdf(MTNC)(BCA)
PPTX
Java interface
Lecture 18
Java interface
Interface in java By Dheeraj Kumar Singh
OOFeatures_revised-2.pptx
Java interfaces
‏‏‏‏‏‏oop lecture 6_١٢٥٩٤٧taiz univercity.pdf
21UCAC31 Java Programming.pdf(MTNC)(BCA)
Java interface

Similar to Lecture 5 interface.pdf (20)

PPTX
Interface
PPTX
Objects and classes in OO Programming concepts
PDF
Interface
PPTX
10-Lecture10_Leeeeeeeeeeeeeeeecture.pptx
PPTX
13. interfaces
PPTX
Interfaces-in-Java.for engineering students pptx
PPTX
Interface in java
PPT
Interfaces .ppt
PPT
Interfaces.ppt
DOCX
Java interface
PDF
Advanced Programming _Abstract Classes vs Interfaces (Java)
PDF
14 interface
PPTX
java_unitffjfjfjjrdteszserfdffvjyurt_6.pptx
PDF
Interfaces in java
PPTX
Interface in Java
PPTX
Unit II Inheritance ,Interface and Packages.pptx
PPT
Interfaces
PDF
Basic_Java_10.pdf
PPT
oops with java modules i & ii.ppt
PDF
Exception handling and packages.pdf
Interface
Objects and classes in OO Programming concepts
Interface
10-Lecture10_Leeeeeeeeeeeeeeeecture.pptx
13. interfaces
Interfaces-in-Java.for engineering students pptx
Interface in java
Interfaces .ppt
Interfaces.ppt
Java interface
Advanced Programming _Abstract Classes vs Interfaces (Java)
14 interface
java_unitffjfjfjjrdteszserfdffvjyurt_6.pptx
Interfaces in java
Interface in Java
Unit II Inheritance ,Interface and Packages.pptx
Interfaces
Basic_Java_10.pdf
oops with java modules i & ii.ppt
Exception handling and packages.pdf
Ad

Recently uploaded (20)

PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
Pre independence Education in Inndia.pdf
PPTX
Lesson notes of climatology university.
PPTX
Institutional Correction lecture only . . .
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
01-Introduction-to-Information-Management.pdf
PDF
Basic Mud Logging Guide for educational purpose
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
STATICS OF THE RIGID BODIES Hibbelers.pdf
Pharma ospi slides which help in ospi learning
Pre independence Education in Inndia.pdf
Lesson notes of climatology university.
Institutional Correction lecture only . . .
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Renaissance Architecture: A Journey from Faith to Humanism
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPH.pptx obstetrics and gynecology in nursing
human mycosis Human fungal infections are called human mycosis..pptx
01-Introduction-to-Information-Management.pdf
Basic Mud Logging Guide for educational purpose
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
O5-L3 Freight Transport Ops (International) V1.pdf
Insiders guide to clinical Medicine.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Ad

Lecture 5 interface.pdf

  • 1. Compiled By: Umm-e-Laila Lecture # 9 1 Interfaces in Java
  • 2. Course Books ◼ Text Book: ◼ Herbert Schildt, Java: The Complete Reference, McGraw-Hill Education, Eleventh Edition ◼ Craig Larman, Applying UML & patterns, 2 edition ◼ Reference Books: ◼ Cay S. Horstmann, Big Java: Early Objects, Wiley, 7th Edition ◼ Herbert Schildt, Java: A Beginner's Guide, McGraw-Hill Education, Eighth Edition 2
  • 3. Course Instructors ◼ Umm-e-Laila ulaila@ssuet.edu.pk Assistant Professor, CED Room Number: BS-04 Tel: 111-994-994, Ext. 536 ◼ Aneeta Siddiqui aarshad@ssuet.edu.pk Assistant Professor, CED Room Number: BS-03 Tel: 111-994-994,
  • 5. What is an Interface ◼ In Java, only single inheritance is permitted. However, Java provides a construct called an interface which can be implemented by a class. ◼ An interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. ◼ Interfaces are similar to abstract classes but with some differences ◼ A class can implement any number of interfaces. In effect using interfaces gives us the benefit of multiple inheritance without many of it’s problems. ◼ Interfaces are compiled into bytecode just like classes. ◼ Interfaces cannot be instantiated. ◼ Can use interface as a data type for variables. ◼ Can also use an interface as the result of a cast
  • 6. What is an Interface cont.. ◼ Interfaces can contain only abstract methods and constants. ◼ An interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behavior. ◼ An interface is a named collection of method definitions (without implementations). ◼ Interface reserve behaviors for classes that implement them. 6
  • 7. What is an Interface cont.. ◼ Methods declared in an interface are always public and abstract, therefore Java compiler will not complain if you omit both keywords ◼ Static methods cannot be declared in the interfaces – these methods are never abstract and do not express behavior of objects ◼ Variables can be declared in the interfaces. They can only be declared as static and final. – Both keyword are assumed by default and can be safely omitted. ◼ Sometimes interfaces declare only constants – be used to effectively import sets of related constants 7
  • 8. Defining an Interface ◼ Defining an interface is similar to creating a new class. ◼ An interface definition has two components: the interface declaration and the interface body. interface Declaration { interfaceBody } ◼ The interfaceDeclaration declares various attributes about the interface such as its name and whether it extends another interface. ◼ The interfaceBody contains the constant and method declarations within the interface 8
  • 9. Interface public interface StockWatcher { final String sunTicker = "SUNW"; final String oracleTicker = "ORCL"; final String ciscoTicker = "CSCO"; void valueChanged(String tickerSymbol, double newValue); } ◼ If you do not specify that your interface is public, your interface will be accessible only to classes that are defined in the same package as the interface 9
  • 10. Implementing an Interface ◼ Include an implements clause in the class declaration. ◼ A class can implement more than one interface (the Java platform supports multiple inheritance for interfaces), so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class. ◼ When implement an interface, either the class must implement all the methods declared in the interface and its superinterfaces, or the class must be declared abstract 10
  • 11. Implementation of Interface syntax public class StockMonitor implements StockWatcher { public void valueChanged(String tickerSymbol,double newValue) { if (tickerSymbol.equals(sunTicker)) { ... } else if (tickerSymbol.equals(oracleTicker)) { ... } else if (tickerSymbol.equals(ciscoTicker)) { ... } } }
  • 12. Properties of Interface ◼ A new interface is a new reference data type. ◼ Interfaces are not instantiated with new, but they have certain properties similar to ordinary classes ◼ You can declare that an object variable will be of that interface type e.g. Comparable x = new Tile(…); Tile y = new Tile(…); if (x.compareTo(y) < 0) … 12
  • 13. Super Interface(Extends Interface) ◼ An interface can extend other interfaces, just as a class can extend or subclass another class. ◼ An interface can extend any number of interfaces. ◼ The list of superinterfaces is a comma-separated list of all the interfaces extended by the new interface modifier interface interfaceID extends comma-delimited-list-of-interfaces { //constants/method signatures } 13
  • 14. Super Interface(cont) ◼ Obviously, any class which implements a “sub-interface” will have to implement each of the methods contained in it’s “super-interfaces” ◼ Two ways of extending interfaces: ❑ Add new methods ❑ Define new constants ◼ Interfaces do not have a single top-level interface. (Like Object class for classes) 14
  • 15. Interface vs. abstract class Interface Abstract class Fields Only constants. By default final Constants and variable data(may contain non final variable) Methods No implementation allowed (no abstract modifier necessary) Abstract or concrete Accessibility Members of a java interface are public by default A member of an abstract class can either be private, protective or public.
  • 16. Interface vs. abstract class (cont) Interface Abstract class Inheritance A subclass can implement many interfaces A subclass can inherit only one class Can extend numerous interfaces Can implement numerous interfaces Cannot extend a class Extends one class
  • 17. Interface vs. abstract class (cont) Interface Abstract class Root none Object (of all classes) names Adjective or Nouns Nouns
  • 18. Interface Example ◼ First Interface standard Remote interface stdremote{ int volume limit=500; public abstract void volume(); void setChannel(); void brightness(); void mute(); } 18
  • 19. ◼ Second Interface ExtendedRemote interface extends ExtRemote{ void autoconfiguration(); void doubly(); void AVL(); } ◼ Third Interface ModernRemote using StdRemote and ExtRemote interface ModernRemote extends StdRemote,ExtRemote {} 19
  • 20. ◼ Abstract Class Tv abstract class Tv{ abstract void Switch on(); abstract void Switch off(); } ◼ Provide Implementation for the given class also show difference if any ◼ Class Sony extends TV implements ModernRemote{} ◼ Class Sony extends TV implements StdRemote, ExtRemote{ } 20
  • 21. 21 Interface - Example VOLUME_LIMIT=500 :int Volume():void Mute():void Brightness():void setChannels(): void <<Interface>> StdRemote <<Interface>> ExtendedRemote AVL():void NetFlix():void PrimeVdo():void autoConfiguration(): void <<Interface>> ModernRemotec
  • 22. 22 Interface - Example <<abstract>> TV abstract SwitchOn():void abstract SwitchOff():void <<Interface>> ModernRemote <<class> SonyTv
  • 23. Example 2 ◼ First Interface BiCycle public interface BiCycle { void Speed(int a); void ApplyBrake(int a); void ChangeGear(int a);} 23
  • 24. Example 2 ◼ Class MyBiCycle public class MyBiCycle implements BiCycle { double speed; int gear; public MyBiCycle(double speed, int gear) { this.speed = speed; this.gear = gear; } public void Speed(int a){ speed+=a; } public void ApplyBrake(int a){ speed-=a; } public void ChangeGear(int a){ gear=a; } public String toString(){ return "BiCycle Speed="+speed+"n BiCycle is on Gear"+gear; } } 24
  • 25. Example 2 ◼ Test Class public class TestMyBiCycle { public static void main(String[] args) { BiCycle bi; bi=new MyBiCycle(50,2); System.out.println(""+bi); } } Output: BiCycle Speed=50.0 BiCycle is on Gear2 25
  • 26. Interfaces Cannot Grow! ◼ Add some functionality to StockWatcher? public interface StockWatcher { final String sunTicker = "SUNW"; final String oracleTicker = "ORCL"; final String ciscoTicker = "CSCO"; void valueChanged(String tickerSymbol, double newValue); void currentValue(String tickerSymbol, double newValue); } ◼ If you make this change, all classes that implement the old interface will break because they don’t implement the interface anymore! 26
  • 27. Default Method in Java Interface( 1.8 version) ◼ If we want to add cadenceRate (or pedaling rate) method in the interface BiCycle . it will break MyBike class therefore java 1.8 provides a default method implementation to avoid this problem. otherwise MyBiCycle need to make changes in it ◼ First Interface BiCycle public interface BiCycle { void Speed(int a); void ApplyBrake(int a); void ChangeGear(int a); void CadenceRate(int a); } 27
  • 28. 1:Create default method in Interface BiCycle public interface BiCycle { void Speed(int a); void ApplyBrake(int a); void ChangeGear(int a); default void CadenceRate(int a){ System.out.println(“Cadence is 120”); } }} 28
  • 29. 2:Create Test Class to show usage of default method public class TestMyBiCycle { public static void main(String[] args) { BiCycle bi; bi=new MyBiCycle(50,2); System.out.println(""+bi); bi.CadenceRate(2); }} output: BiCycle Speed=50.0 BiCycle is on Gear2 Cadence is 120 29
  • 30. 3:Implements Cadence in Class MyBiCycle public class MyBiCycle implements BiCycle { double speed; int gear; double cadence; public MyBiCycle(double speed, int gear, double cadence) { this.speed = speed; this.gear = gear; this.cadence=cadence; } public void Speed(int a){ speed+=a; } public void ApplyBrake(int a){ speed-=a; } public void ChangeGear(int a){ gear=a; } public String toString(){ return "BiCycle Speed="+speed+"n BiCycle is on Gear"+gear;+ "n with cadence rate"+cadence;} public void CadenceRate(int a){ cadence+=a; } 30
  • 31. 4: Test class for default method public class TestMyBiCycle { public static void main(String[] args) { BiCycle bi; bi=new MyBiCycle(50,2,10); System.out.println(""+bi); bi.CadenceRate(2); System.out.println(""+bi); } } Output: BiCycle Speed=50.0 BiCycle is on Gear2 with cadence rate10.0 BiCycle Speed=50.0 BiCycle is on Gear2 with cadence rate12.0 31
  • 32. 32 Interface - Example speak() Politician Priest <<Interface>> Speaker speak() speak() Lecturer speak()
  • 33. 33 Implementing Interfaces Example class Politician implements Speaker { public void speak(){ System.out.println(“Talk politics”); } } class Priest implements Speaker { public void speak(){ System.out.println(“Religious Talks”); } } class Lecturer implements Speaker { public void speak(){ System.out.println(“Talks Object Oriented Design and Programming!”); } }
  • 34. 34 Student Assessment Example ◼ Consider a university where students who participate in the national games or Olympics are given some grace marks. Therefore, the final marks awarded = Exam_Marks + Sports_Grace_Marks. A class diagram representing this scenario is as follow: Student Sports Exam Results extends extends implements
  • 35. 35 Software Implementation class Student { // student no and access methods } interface Sport { // sports grace marks (say 5 marks) and abstract methods } class Exam extends Student { // example marks (test1 and test 2 marks) and access methods } class Results extends Exam implements Sport { // implementation of abstract methods of Sport interface // other methods to compute total marks = test1+test2+sports_grace_marks; // other display or final results access methods }
  • 36. Summary ◼ An abstract method has no method body. An abstract class contains abstract methods. ◼ An interface is a collection of abstract methods and constants. A class implements an interface by declaring it in its implements clause, and providing a method body for each abstract method. 36