SlideShare a Scribd company logo
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

More Related Content

PDF
The origin: Init (presentation version)
Tzung-Bi Shih
 
PDF
The origin: Init (compact version)
Tzung-Bi Shih
 
PDF
Study: The Future of VR, AR and Self-Driving Cars
LinkedIn
 
PPT
Chapter 5 (OOP Principles).ppt
henokmetaferia1
 
PDF
itft-Inheritance in java
Atul Sehdev
 
PPT
Ap Power Point Chpt7
dplunkett
 
PPTX
Java chapter 5
Abdii Rashid
 
PPTX
Core java oop
Parth Shah
 
The origin: Init (presentation version)
Tzung-Bi Shih
 
The origin: Init (compact version)
Tzung-Bi Shih
 
Study: The Future of VR, AR and Self-Driving Cars
LinkedIn
 
Chapter 5 (OOP Principles).ppt
henokmetaferia1
 
itft-Inheritance in java
Atul Sehdev
 
Ap Power Point Chpt7
dplunkett
 
Java chapter 5
Abdii Rashid
 
Core java oop
Parth Shah
 

Similar to Inheritance (20)

PPTX
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
PPTX
object oriented programming unit two ppt
isiagnel2
 
PPT
Java: Inheritance
Tareq Hasan
 
PDF
java-06inheritance
Arjun Shanka
 
PPTX
OBJECT ORIENTED PROGRAMMING STRUCU2.pptx
JeevaR43
 
PPTX
Unit3 inheritance
Kalai Selvi
 
PPTX
Java session2
Rajeev Kumar
 
PPT
L7 inheritance
teach4uin
 
PPT
L7 inheritance
teach4uin
 
PPTX
Lecture 6 inheritance
manish kumar
 
PPTX
Chap-3 Inheritance.pptx
chetanpatilcp783
 
PPT
A457405934_21789_26_2018_Inheritance.ppt
RithwikRanjan
 
PPTX
Ch5 inheritance
HarshithaAllu
 
PPT
9781439035665 ppt ch10
Terry Yoast
 
PPT
Chap11
Terry Yoast
 
PPT
Java inheritance
Arati Gadgil
 
PPTX
Chap3 inheritance
raksharao
 
PPTX
Unit3 part2-inheritance
DevaKumari Vijay
 
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
object oriented programming unit two ppt
isiagnel2
 
Java: Inheritance
Tareq Hasan
 
java-06inheritance
Arjun Shanka
 
OBJECT ORIENTED PROGRAMMING STRUCU2.pptx
JeevaR43
 
Unit3 inheritance
Kalai Selvi
 
Java session2
Rajeev Kumar
 
L7 inheritance
teach4uin
 
L7 inheritance
teach4uin
 
Lecture 6 inheritance
manish kumar
 
Chap-3 Inheritance.pptx
chetanpatilcp783
 
A457405934_21789_26_2018_Inheritance.ppt
RithwikRanjan
 
Ch5 inheritance
HarshithaAllu
 
9781439035665 ppt ch10
Terry Yoast
 
Chap11
Terry Yoast
 
Java inheritance
Arati Gadgil
 
Chap3 inheritance
raksharao
 
Unit3 part2-inheritance
DevaKumari Vijay
 
Ad

More from Sardar Alam (17)

PPTX
Undoing of mental illness -- seek help
Sardar Alam
 
PDF
introduction to python
Sardar Alam
 
PPT
Operator Overloading
Sardar Alam
 
PPT
skin disease classification
Sardar Alam
 
PDF
filters for noise in image processing
Sardar Alam
 
PDF
Noise Models
Sardar Alam
 
PDF
Noise Models
Sardar Alam
 
PPT
Introduction to machine learningunsupervised learning
Sardar Alam
 
PPTX
Opengl texturing
Sardar Alam
 
PPTX
Mathematics fundamentals
Sardar Alam
 
PPTX
3 d graphics with opengl part 2
Sardar Alam
 
PPTX
3 d graphics with opengl part 1
Sardar Alam
 
PPTX
3 d graphics basics
Sardar Alam
 
PPTX
2 d transformations
Sardar Alam
 
PDF
Gui
Sardar Alam
 
PDF
Arrays string handling java packages
Sardar Alam
 
PDF
Java basics
Sardar Alam
 
Undoing of mental illness -- seek help
Sardar Alam
 
introduction to python
Sardar Alam
 
Operator Overloading
Sardar Alam
 
skin disease classification
Sardar Alam
 
filters for noise in image processing
Sardar Alam
 
Noise Models
Sardar Alam
 
Noise Models
Sardar Alam
 
Introduction to machine learningunsupervised learning
Sardar Alam
 
Opengl texturing
Sardar Alam
 
Mathematics fundamentals
Sardar Alam
 
3 d graphics with opengl part 2
Sardar Alam
 
3 d graphics with opengl part 1
Sardar Alam
 
3 d graphics basics
Sardar Alam
 
2 d transformations
Sardar Alam
 
Arrays string handling java packages
Sardar Alam
 
Java basics
Sardar Alam
 
Ad

Recently uploaded (20)

PPTX
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
PDF
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
PDF
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
PDF
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
PDF
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
ESUG
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
PPTX
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
PDF
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PDF
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
PDF
New Download MiniTool Partition Wizard Crack Latest Version 2025
imang66g
 
PDF
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
PPTX
Role Of Python In Programing Language.pptx
jaykoshti048
 
PDF
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
PDF
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
PDF
Summary Of Odoo 18.1 to 18.4 : The Way For Odoo 19
CandidRoot Solutions Private Limited
 
PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PDF
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
PDF
Protecting the Digital World Cyber Securit
dnthakkar16
 
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
ESUG
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
New Download MiniTool Partition Wizard Crack Latest Version 2025
imang66g
 
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
Role Of Python In Programing Language.pptx
jaykoshti048
 
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
Summary Of Odoo 18.1 to 18.4 : The Way For Odoo 19
CandidRoot Solutions Private Limited
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
Protecting the Digital World Cyber Securit
dnthakkar16
 

Inheritance

  • 1. 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!
  • 2. 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:
  • 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 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
  • 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 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
  • 13. 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.!
  • 14. 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! {! ![...]!
  • 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! ! 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?!
  • 17. 8-Apr-14 Abstract Classes and Interfaces
  • 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 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. 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
  • 21. 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. 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
  • 23. 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. 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 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 { … }
  • 29. 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
  • 30. 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. 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. 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. 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