Inheritance! 
The objectives of this chapter are:! 
! 
! To explore the concept and implications of inheritance! 
! Polymorphism! 
! To define the syntax of inheritance in Java! 
! To understand the class hierarchy of Java! 
! To examine the effect of inheritance on constructors!
Terminology! 
! Inheritance is a fundamental Object Oriented concept! 
! 
! A class can be defined as a "subclass" of another class.! 
! The subclass inherits all data attributes of its superclass! 
! The subclass inherits all methods of its superclass! 
! The subclass inherits all associations of its superclass! 
! 
! The subclass can:! 
! Add new functionality! 
! Use inherited functionality! 
! Override inherited functionality! 
Person 
- name: String 
- dob: Date 
Employee 
- employeeID: int 
- salary: int 
- startDate: Date 
superclass: 
subclass:
What really happens?! 
! When an object is created using new, the system must 
allocate enough memory to hold all its instance variables.! 
! This includes any inherited instance variables! 
! 
! In this example, we can say that an Employee "is a kind of" 
Person. ! 
! An Employee object inherits all of the attributes, methods and 
associations of Person! 
Person 
- name: String 
- dob: Date 
Employee 
- employeeID: int 
- salary: int 
- startDate: Date 
Person 
name = "John Smith" 
dob = Jan 13, 1954 
Employee 
name = "Sally Halls" 
dob = Mar 15, 1968 
employeeID = 37518 
salary = 65000 
startDate = Dec 15, 
2000 
is a kind of
Inheritance in Java! 
! Inheritance is declared using the "extends" keyword! 
! If inheritance is not defined, the class extends a class called Object! 
! 
Person 
- name: String 
- dob: Date 
Employee 
- employeeID: int 
- salary: int 
- startDate: Date 
public class Person! 
{! 
!private String name;! 
!private Date dob;! 
![...]! 
public class Employee extends Person! 
{! 
!private int employeID;! 
!private int salary;! 
!private Date startDate;! 
![...]! 
Employee anEmployee = new Employee();!
Inheritance Hierarchy! 
! Each Java class has one (and only one) superclass.! 
! C++ allows for multiple inheritance! 
! 
! Inheritance creates a class hierarchy! 
! Classes higher in the hierarchy are more general and more abstract! 
! Classes lower in the hierarchy are more specific and concrete! 
! There is no limit to the Class 
number of subclasses a class 
can have! 
! 
! There is no limit to the depth 
of the class tree.! 
Class 
Class 
Class 
Class 
Class 
Class 
Class
The class called Object! 
! At the very top of the inheritance tree is a class called Object! 
! 
! All Java classes inherit from Object.! 
! All objects have a common ancestor! 
! This is different from C++! 
! 
! The Object class is defined in the java.lang package! 
! Examine it in the Java API Specification! 
Object
Constructors and Initialization! 
! Classes use constructors to initialize instance variables! 
! When a subclass object is created, its constructor is called.! 
! It is the responsibility of the subclass constructor to invoke the 
appropriate superclass constructors so that the instance variables 
defined in the superclass are properly initialized! 
! 
! Superclass constructors can be called using the "super" 
keyword in a manner similar to "this"! 
! It must be the first line of code in the constructor! 
! 
! If a call to super is not made, the system will automatically 
attempt to invoke the no-argument constructor of the 
superclass.!
Constructors - Example! 
public class BankAccount! 
{! 
!private String ownersName;! 
!private int accountNumber;! 
!private float balance;! 
! 
!public BankAccount(int anAccountNumber, String aName)! 
!{! 
! !accountNumber = anAccountNumber;! 
! !ownersName = aName;! 
!}! 
![...]! 
}! 
! 
public class OverdraftAccount extends BankAccount! 
{! 
!private float overdraftLimit;! 
! 
!public OverdraftAccount(int anAccountNumber, String aName, float aLimit)! 
!{! 
! !super(anAccountNumber, aName);! 
! !overdraftLimit = aLimit;! 
!}! 
}!
Method Overriding! 
! Subclasses inherit all methods from their superclass! 
! Sometimes, the implementation of the method in the superclass does 
not provide the functionality required by the subclass.! 
! In these cases, the method must be overridden.! 
! 
! To override a method, provide an implementation in the 
subclass.! 
! The method in the subclass MUST have the exact same signature as 
the method it is overriding.! 
! 
!
Method overriding - Example! 
public class BankAccount! 
{! 
!private String ownersName;! 
!private int accountNumber;! 
!protected float balance;! 
! 
!public void deposit(float anAmount)! 
!{! 
! !if (anAmount>0.0)! 
! ! !balance = balance + anAmount;! 
!}! 
! 
!public void withdraw(float anAmount)! 
!{! 
! !if ((anAmount>0.0) && (balance>anAmount))! 
! ! !balance = balance - anAmount;! 
!}! 
! 
!public float getBalance()! 
!{! 
! !return balance;! 
!}! 
}!
Method overriding - Example! 
public class OverdraftAccount extends BankAccount! 
{! 
!private float limit;! 
! 
!public void withdraw(float anAmount)! 
!{! 
! !if ((anAmount>0.0) && (getBalance()+limit>anAmount))! 
! ! !balance = balance - anAmount;! 
!}! 
! 
}!
Object References and Inheritance! 
! Inheritance defines "a kind of" relationship.! 
! In the previous example, OverdraftAccount "is a kind of" BankAccount! 
! 
! Because of this relationship, programmers can "substitute" 
object references.! 
! A superclass reference can refer to an instance of the superclass OR an 
instance of ANY class which inherits from the superclass.! 
! 
! BankAccount anAccount = new BankAccount(123456, "Craig");! 
! 
BankAccount account1 = new OverdraftAccount(3323, "John", 1000.0);! 
anAccount 
BankAccount 
name = "Craig" 
accountNumber = 123456 
account1 
OverdraftAccount 
name = "John" 
accountNumber = 3323 
limit = 1000.0
Polymorphism! 
! In the previous slide, the two variables are defined to have 
the same type at compile time: BankAccount! 
! However, the types of objects they are referring to at runtime are 
different! 
! 
! What happens when the withdraw method is invoked on each 
object?! 
! anAccount refers to an instance of BankAccount. Therefore, the 
withdraw method defined in BankAccount is invoked.! 
! account1 refers to an instance of OverdraftAccount. Therefore, the 
withdraw method defined in OverdraftAccount is invoked.! 
! 
! Polymorphism is: The method being invoked on an object is 
determined AT RUNTIME and is based on the type of the 
object receiving the message.!
Final Methods and Final Classes! 
! Methods can be qualified with the final modifier! 
! Final methods cannot be overridden.! 
! This can be useful for security purposes.! 
public final boolean validatePassword(String username, String Password)! 
{! 
![...]! 
! Classes can be qualified with the final modifier! 
! The class cannot be extended! 
! This can be used to improve performance. Because there an be no 
subclasses, there will be no polymorphic overhead at runtime.! 
public final class Color! 
{! 
![...]!
Virtual Functions! 
! Every non-static method in JAVA is by default virtual 
method! 
! Except final and private methods. ! 
! The methods which cannot be inherited for polymorphic 
behavior is not a virtual method.! 
! In Java there is no keyword names virtual!
Review! 
! What is inheritance? What is a superclass? What is a subclass?! 
! Which class is at the top of the class hierarchy in Java?! 
! What are the constructor issues surrounding inheritance?! 
! What is method overriding? What is polymorphism? How are they 
related?! 
! What is a final method? What is a final class?!
8-Apr-14 
Abstract Classes and Interfaces
18 
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
19 
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
20 
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” 
– 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 
21
22 
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? 
23 
" 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
24 
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
25 
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
26 
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)
27 
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 
28 
" 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) {...}; 
29 
} 
– 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 { 
30 
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 { ... }
31 
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
32 
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
33 
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?
34 
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
35 
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
36 
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

Inheritance

  • 1.
    Inheritance! The objectivesof this chapter are:! ! ! To explore the concept and implications of inheritance! ! Polymorphism! ! To define the syntax of inheritance in Java! ! To understand the class hierarchy of Java! ! To examine the effect of inheritance on constructors!
  • 2.
    Terminology! ! Inheritanceis a fundamental Object Oriented concept! ! ! A class can be defined as a "subclass" of another class.! ! The subclass inherits all data attributes of its superclass! ! The subclass inherits all methods of its superclass! ! The subclass inherits all associations of its superclass! ! ! The subclass can:! ! Add new functionality! ! Use inherited functionality! ! Override inherited functionality! Person - name: String - dob: Date Employee - employeeID: int - salary: int - startDate: Date superclass: subclass:
  • 3.
    What really happens?! ! When an object is created using new, the system must allocate enough memory to hold all its instance variables.! ! This includes any inherited instance variables! ! ! In this example, we can say that an Employee "is a kind of" Person. ! ! An Employee object inherits all of the attributes, methods and associations of Person! Person - name: String - dob: Date Employee - employeeID: int - salary: int - startDate: Date Person name = "John Smith" dob = Jan 13, 1954 Employee name = "Sally Halls" dob = Mar 15, 1968 employeeID = 37518 salary = 65000 startDate = Dec 15, 2000 is a kind of
  • 4.
    Inheritance in Java! ! Inheritance is declared using the "extends" keyword! ! If inheritance is not defined, the class extends a class called Object! ! Person - name: String - dob: Date Employee - employeeID: int - salary: int - startDate: Date public class Person! {! !private String name;! !private Date dob;! ![...]! public class Employee extends Person! {! !private int employeID;! !private int salary;! !private Date startDate;! ![...]! Employee anEmployee = new Employee();!
  • 5.
    Inheritance Hierarchy! !Each Java class has one (and only one) superclass.! ! C++ allows for multiple inheritance! ! ! Inheritance creates a class hierarchy! ! Classes higher in the hierarchy are more general and more abstract! ! Classes lower in the hierarchy are more specific and concrete! ! There is no limit to the Class number of subclasses a class can have! ! ! There is no limit to the depth of the class tree.! Class Class Class Class Class Class Class
  • 6.
    The class calledObject! ! At the very top of the inheritance tree is a class called Object! ! ! All Java classes inherit from Object.! ! All objects have a common ancestor! ! This is different from C++! ! ! The Object class is defined in the java.lang package! ! Examine it in the Java API Specification! Object
  • 7.
    Constructors and Initialization! ! Classes use constructors to initialize instance variables! ! When a subclass object is created, its constructor is called.! ! It is the responsibility of the subclass constructor to invoke the appropriate superclass constructors so that the instance variables defined in the superclass are properly initialized! ! ! Superclass constructors can be called using the "super" keyword in a manner similar to "this"! ! It must be the first line of code in the constructor! ! ! If a call to super is not made, the system will automatically attempt to invoke the no-argument constructor of the superclass.!
  • 8.
    Constructors - Example! public class BankAccount! {! !private String ownersName;! !private int accountNumber;! !private float balance;! ! !public BankAccount(int anAccountNumber, String aName)! !{! ! !accountNumber = anAccountNumber;! ! !ownersName = aName;! !}! ![...]! }! ! public class OverdraftAccount extends BankAccount! {! !private float overdraftLimit;! ! !public OverdraftAccount(int anAccountNumber, String aName, float aLimit)! !{! ! !super(anAccountNumber, aName);! ! !overdraftLimit = aLimit;! !}! }!
  • 9.
    Method Overriding! !Subclasses inherit all methods from their superclass! ! Sometimes, the implementation of the method in the superclass does not provide the functionality required by the subclass.! ! In these cases, the method must be overridden.! ! ! To override a method, provide an implementation in the subclass.! ! The method in the subclass MUST have the exact same signature as the method it is overriding.! ! !
  • 10.
    Method overriding -Example! public class BankAccount! {! !private String ownersName;! !private int accountNumber;! !protected float balance;! ! !public void deposit(float anAmount)! !{! ! !if (anAmount>0.0)! ! ! !balance = balance + anAmount;! !}! ! !public void withdraw(float anAmount)! !{! ! !if ((anAmount>0.0) && (balance>anAmount))! ! ! !balance = balance - anAmount;! !}! ! !public float getBalance()! !{! ! !return balance;! !}! }!
  • 11.
    Method overriding -Example! public class OverdraftAccount extends BankAccount! {! !private float limit;! ! !public void withdraw(float anAmount)! !{! ! !if ((anAmount>0.0) && (getBalance()+limit>anAmount))! ! ! !balance = balance - anAmount;! !}! ! }!
  • 12.
    Object References andInheritance! ! Inheritance defines "a kind of" relationship.! ! In the previous example, OverdraftAccount "is a kind of" BankAccount! ! ! Because of this relationship, programmers can "substitute" object references.! ! A superclass reference can refer to an instance of the superclass OR an instance of ANY class which inherits from the superclass.! ! ! BankAccount anAccount = new BankAccount(123456, "Craig");! ! BankAccount account1 = new OverdraftAccount(3323, "John", 1000.0);! anAccount BankAccount name = "Craig" accountNumber = 123456 account1 OverdraftAccount name = "John" accountNumber = 3323 limit = 1000.0
  • 13.
    Polymorphism! ! Inthe previous slide, the two variables are defined to have the same type at compile time: BankAccount! ! However, the types of objects they are referring to at runtime are different! ! ! What happens when the withdraw method is invoked on each object?! ! anAccount refers to an instance of BankAccount. Therefore, the withdraw method defined in BankAccount is invoked.! ! account1 refers to an instance of OverdraftAccount. Therefore, the withdraw method defined in OverdraftAccount is invoked.! ! ! Polymorphism is: The method being invoked on an object is determined AT RUNTIME and is based on the type of the object receiving the message.!
  • 14.
    Final Methods andFinal Classes! ! Methods can be qualified with the final modifier! ! Final methods cannot be overridden.! ! This can be useful for security purposes.! public final boolean validatePassword(String username, String Password)! {! ![...]! ! Classes can be qualified with the final modifier! ! The class cannot be extended! ! This can be used to improve performance. Because there an be no subclasses, there will be no polymorphic overhead at runtime.! public final class Color! {! ![...]!
  • 15.
    Virtual Functions! !Every non-static method in JAVA is by default virtual method! ! Except final and private methods. ! ! The methods which cannot be inherited for polymorphic behavior is not a virtual method.! ! In Java there is no keyword names virtual!
  • 16.
    Review! ! Whatis inheritance? What is a superclass? What is a subclass?! ! Which class is at the top of the class hierarchy in Java?! ! What are the constructor issues surrounding inheritance?! ! What is method overriding? What is polymorphism? How are they related?! ! What is a final method? What is a final class?!
  • 17.
  • 18.
    18 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
  • 19.
    19 Abstract classesI " 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
  • 20.
    20 Abstract classesII " 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
  • 21.
    Why have abstractclasses? " 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 21
  • 22.
    22 An exampleabstract 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
  • 23.
    Why have abstractmethods? 23 " 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
  • 24.
    24 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
  • 25.
    25 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
  • 26.
    26 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)
  • 27.
    27 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
  • 28.
    Implementing an interfaceI " 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 28 " Example: class MyListener implements KeyListener, ActionListener { … }
  • 29.
    Implementing an interfaceII " 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) {...}; 29 } – The “...” indicates actual code that you must supply " Now you can create a new MyKeyListener
  • 30.
    Partially implementing anInterface " It is possible to define some but not all of the methods defined in an interface: abstract class MyKeyListener implements KeyListener { 30 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 { ... }
  • 31.
    31 What areinterfaces 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
  • 32.
    32 How touse 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
  • 33.
    33 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?
  • 34.
    34 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
  • 35.
    35 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
  • 36.
    36 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