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

Similar to Inheritance

Preexisting code, please useMain.javapublic class Main { p.pdf
Preexisting code, please useMain.javapublic class Main {    p.pdfPreexisting code, please useMain.javapublic class Main {    p.pdf
Preexisting code, please useMain.javapublic class Main { p.pdf
rd1742
 
OOP's Part 1
OOP's Part 1OOP's Part 1
OOP's Part 1
Saravanakumar R
 
Object-oriented programming 3.pptx
Object-oriented programming 3.pptxObject-oriented programming 3.pptx
Object-oriented programming 3.pptx
Adikhan27
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
Alex Koppel
 
Introduction to JavaScript design patterns
Introduction to JavaScript design patternsIntroduction to JavaScript design patterns
Introduction to JavaScript design patterns
Jeremy Duvall
 
Oops
OopsOops
OOPS Characteristics (With Examples in PHP)
OOPS Characteristics (With Examples in PHP)OOPS Characteristics (With Examples in PHP)
OOPS Characteristics (With Examples in PHP)
baabtra.com - No. 1 supplier of quality freshers
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
Shreyans Pathak
 
Nested class in java
Nested class in javaNested class in java
Nested class in java
ChiradipBhattacharya
 
04cpp inh
04cpp inh04cpp inh
04cpp inh
Jihin Raju
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
Sherihan Anver
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
Hari kiran G
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
Terry Yoast
 
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
AshwathGupta
 
Unusual C# - OOP
Unusual C# - OOPUnusual C# - OOP
Unusual C# - OOP
Medhat Dawoud
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
venud11
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oop
colleges
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
Epsiba1
 
Java object oriented programming - OOPS
Java object oriented programming - OOPSJava object oriented programming - OOPS
Java object oriented programming - OOPS
rithustutorials
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
Rakesh Madugula
 

Similar to Inheritance (20)

Preexisting code, please useMain.javapublic class Main { p.pdf
Preexisting code, please useMain.javapublic class Main {    p.pdfPreexisting code, please useMain.javapublic class Main {    p.pdf
Preexisting code, please useMain.javapublic class Main { p.pdf
 
OOP's Part 1
OOP's Part 1OOP's Part 1
OOP's Part 1
 
Object-oriented programming 3.pptx
Object-oriented programming 3.pptxObject-oriented programming 3.pptx
Object-oriented programming 3.pptx
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
Introduction to JavaScript design patterns
Introduction to JavaScript design patternsIntroduction to JavaScript design patterns
Introduction to JavaScript design patterns
 
Oops
OopsOops
Oops
 
OOPS Characteristics (With Examples in PHP)
OOPS Characteristics (With Examples in PHP)OOPS Characteristics (With Examples in PHP)
OOPS Characteristics (With Examples in PHP)
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
Nested class in java
Nested class in javaNested class in java
Nested class in java
 
04cpp inh
04cpp inh04cpp inh
04cpp inh
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
 
Unusual C# - OOP
Unusual C# - OOPUnusual C# - OOP
Unusual C# - OOP
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oop
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
Java object oriented programming - OOPS
Java object oriented programming - OOPSJava object oriented programming - OOPS
Java object oriented programming - OOPS
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
 

More from Sardar Alam

Undoing of mental illness -- seek help
Undoing of mental illness -- seek helpUndoing of mental illness -- seek help
Undoing of mental illness -- seek help
Sardar Alam
 
introduction to python
introduction to pythonintroduction to python
introduction to python
Sardar Alam
 
Operator Overloading
Operator Overloading  Operator Overloading
Operator Overloading
Sardar Alam
 
skin disease classification
skin disease classificationskin disease classification
skin disease classification
Sardar Alam
 
filters for noise in image processing
filters for noise in image processingfilters for noise in image processing
filters for noise in image processing
Sardar Alam
 
Noise Models
Noise ModelsNoise Models
Noise Models
Sardar Alam
 
Noise Models
Noise ModelsNoise Models
Noise Models
Sardar Alam
 
Introduction to machine learningunsupervised learning
Introduction to machine learningunsupervised learningIntroduction to machine learningunsupervised learning
Introduction to machine learningunsupervised learning
Sardar Alam
 
Opengl texturing
Opengl texturingOpengl texturing
Opengl texturing
Sardar Alam
 
Mathematics fundamentals
Mathematics fundamentalsMathematics fundamentals
Mathematics fundamentals
Sardar Alam
 
3 d graphics with opengl part 2
3 d graphics with opengl  part 23 d graphics with opengl  part 2
3 d graphics with opengl part 2
Sardar Alam
 
3 d graphics with opengl part 1
3 d graphics with opengl part 13 d graphics with opengl part 1
3 d graphics with opengl part 1
Sardar Alam
 
3 d graphics basics
3 d graphics basics3 d graphics basics
3 d graphics basics
Sardar Alam
 
2 d transformations
2 d transformations2 d transformations
2 d transformations
Sardar Alam
 
Gui
GuiGui
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packages
Sardar Alam
 
Java basics
Java basicsJava basics
Java basics
Sardar Alam
 

More from Sardar Alam (17)

Undoing of mental illness -- seek help
Undoing of mental illness -- seek helpUndoing of mental illness -- seek help
Undoing of mental illness -- seek help
 
introduction to python
introduction to pythonintroduction to python
introduction to python
 
Operator Overloading
Operator Overloading  Operator Overloading
Operator Overloading
 
skin disease classification
skin disease classificationskin disease classification
skin disease classification
 
filters for noise in image processing
filters for noise in image processingfilters for noise in image processing
filters for noise in image processing
 
Noise Models
Noise ModelsNoise Models
Noise Models
 
Noise Models
Noise ModelsNoise Models
Noise Models
 
Introduction to machine learningunsupervised learning
Introduction to machine learningunsupervised learningIntroduction to machine learningunsupervised learning
Introduction to machine learningunsupervised learning
 
Opengl texturing
Opengl texturingOpengl texturing
Opengl texturing
 
Mathematics fundamentals
Mathematics fundamentalsMathematics fundamentals
Mathematics fundamentals
 
3 d graphics with opengl part 2
3 d graphics with opengl  part 23 d graphics with opengl  part 2
3 d graphics with opengl part 2
 
3 d graphics with opengl part 1
3 d graphics with opengl part 13 d graphics with opengl part 1
3 d graphics with opengl part 1
 
3 d graphics basics
3 d graphics basics3 d graphics basics
3 d graphics basics
 
2 d transformations
2 d transformations2 d transformations
2 d transformations
 
Gui
GuiGui
Gui
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packages
 
Java basics
Java basicsJava basics
Java basics
 

Recently uploaded

Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.
AnkitaPandya11
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
gapen1
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
YAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring detailsYAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring details
NishanthaBulumulla1
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
YousufSait3
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
Preparing Non - Technical Founders for Engaging a Tech Agency
Preparing Non - Technical Founders for Engaging  a  Tech AgencyPreparing Non - Technical Founders for Engaging  a  Tech Agency
Preparing Non - Technical Founders for Engaging a Tech Agency
ISH Technologies
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 

Recently uploaded (20)

Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
YAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring detailsYAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring details
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
Preparing Non - Technical Founders for Engaging a Tech Agency
Preparing Non - Technical Founders for Engaging  a  Tech AgencyPreparing Non - Technical Founders for Engaging  a  Tech Agency
Preparing Non - Technical Founders for Engaging a Tech Agency
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 

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