SlideShare a Scribd company logo
Chapter 8 Inheritance and Polymorphism
Oum Saokosal, Chief of Computer Science
National Polytechnic Institute of Cambodia
Tel: (855)-12-252-752
E-mail: oum_saokosal@yahoo.com
1
Inheritance
Chapter 8 Inheritance and Polymorphism
2
Inheritance
1. What is Inheritance?
2. Why Inheritance?
3. How to use it?
4. Superclass & Subclass
5. Using keyword super
6. Overriding Methods
7. The Object class
3
1. What is Inheritance?
4
1. What is Inheritance? (1)
• OOP has 3 features:
1. Class Encapsulation
2. Inheritance
3. Polymorphism
• OOP allows you to derive (create) new objects from
existing classes. E.g.
– You can create objects from a class:
• Circle cir = new Circle();
• Word w = new Word(“N P I C”);
5
1. What is Inheritance? (2)
• But OOP has other mechanisms. One of them is
called Inheritance.
• Inheritance is a mechanism to make classes inherit
properties/methods from an existing class.
• Inherit (v) ¬TTYlekrþtMENl¦
• Inheritance (n) receiving properties
6
1. What is Inheritance? (3)
• In fact, every class in Java is always inherited
from an existing class, either explicitly or
implicitly.
• In Java, every class is inherited from
java.lang.Object.
To be clear, please look at an example at next
slide.
7
1. What is Inheritance? (4) - Example
1. Please create a blank class, say, BlankSample
public class BlankSample {
}
1. Then create a test class, say, TestBlank
public class TestBlank {
public static void main(String[] args){
BlankSample bs = new BlankSample();
System.out.print(bs.toString());
}
}
The question is why we can call bs.toString()?
If we look at BlankSample, there is toString(). Why? 8
1. What is Inheritance? (5) - IDE
9
1. What is Inheritance? (6)
• Where these methods come from?
They are from java.lang.Object. Because every class in
Java inherits from java.lang.Object.
• To be sure, please look at the API and find out
java.lang.Object. Then see its methods.
– clone(), equals(Object obj),
finalize(), getClass(),
hashCode(), notify(),
notifyAll(), toString() and
wait()
10
2. Why Inheritance?
11
2. Why Inheritance?
• Classes often share capabilities
• We want to avoid re-coding these capabilities
• Reuse of these would be best to
– Improve maintainability
– Reduce cost
– Improve “real world” modeling
12
2. Why Inheritance? -Benefits
• No need to reinvent the wheel.
• Allows us to build on existing codes without having
to copy it and past it or rewrite it again, etc.
• To create the subclass, we need to program only
the differences between the superclass and the
subclass that inherits from it.
• Make class more flexible.
13
3. How to use it?
14
3. How to use it? (1)
• In Java, to enable a class inherit an existing class, we have to use a
keyword “extends”. For example, we have Circle class:
public class Circle{
private double radius;
public Circle(){}
public Circle(double radius){
this.radius = radius;
}
public void setRadius(double radius){
this.radius = radius;
}
public double findArea(){
return radius * radius *3.14;
}
}
15
3. How to use it? (2)
• Then we want another class, say, TestCircle, inherits from the
Circle class.
public class TestCircle extends Circle{
public static void main(String[] args){
TestCircle tc1 = new TestCircle();
tc1.setRadius(5.0);
System.out.println(tc1.findArea());
}
}
• Please note that TestCircle didn’t define setRadius() and getArea()
methods but it could use the methods.
• The reason is TestCircle inherits from Circle class.
16
3. How to use it? – Note (1)
• Usually inheritance is used to improve features of
an existing class.
• Please look at the code on page 288, listing 8.1
First Version of the Cylinder class.
– The Circle has already the findArea()
– So the formula to find Cylinder’s Volume is :
volume = Area * length
17
3. How to use it? – Note (2)
public class Cylinder extends Circle {
private double length = 1;
public double getLength(){
return length;
}
public void setLength(double length){
this.length = length;
}
public double findVolume(){
return findArea() * length;
}
}
18
3. How to use it? – Note (3)
public class TestCylinder {
public static void main(String[] args){
Cylinder c1 = new Cylinder();
c1.setRadius(2.5); // from Circle
c1.setLength(5); // from Cylinder
System.out.println(c1.findVolume());
}
}
• Please note that the cylinder’s object, c1, could call a method,
“setLength()”, from Cylinder class and also could call a method,
“setRadius()”, from Circle class.
19
4. Superclass & Subclass
20
4. Superclass & Subclass (1)
• The cylinder class inherits features from
circle class. Then,
– Cylinder is subclass
– Circle is superclass
Super inherit Subclass
21
Circle Cylinder
4. Superclass & Subclass (2)
Quick Check:
C1 <- C2 <- C3 <- C4
What are superclass and subclass?
- C1 is the superclass of C2, C3, & C4
- C2 are the subclass of C1 and the superclass of C3 & C4
- C3 are the subclass of C1 & C2 and the superclass of C4
- C4 is the subclass of C1, C2 & C3
• It means if we call the final subclass, e.g. C4, then we can
use features from C1, C2, C3, and, of course, C4 itself.
22
4. Superclass & Subclass (3) – Java API
• Please check API Documentation: Javax.swing.JFrame is the
subclass of Frame,Window,Container,Component,Object. So if we
use JFrame, it means we use features from all of the superclasses.
23
4. Superclass & Subclass (4)
• Sample of using JFrame
import javax.swing.*;
public class TestJFrame extends JFrame {
public static void main(String[] args){
TestJFrame frame = new TestJFrame();
frame.setTitle("Hi I am JFrame");
frame.setSize(400,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
}
} // Note the underline codes
24
5. Using keyword super
25
5. Using keyword super (1)
• super is used to call:
1. Constructors of the superclass
2. Methods of the superclass
26
Using keyword super (2)
• To call constructors of the superclass
super(); //call no-arg constructor
super(5.0); //call arg constructor
• Note
super():
1. MUST be written in the 1st
line of subclass constructors
2. Cannot be written in other methods
3. Is the only way to call superclass constructor.
27
Using keyword super (3)
• To call methods of the superclass
super.setRadius(5); // setRadius(5);
super.findArea();
super.toString();
Note:
• This keyword is not always used to call methods from superclass.
• We can call superclass methods by calling directly the methods name.
Please look at slide # 14.
• However, super is used not to confuse with the name of the overriding
methods.
28
6. Overriding Methods
29
Overriding Methods (1)
In the real world:
• Researchers sometimes never invent or find a new
thing. In fact, they just improve an existing thing.
• To improve the thing, they just:
1. Add new features
2. Modify existing features.
30
Overriding Methods (2)
In OOP:
It is true to the both things above. The inheritance
helps us to do these. We can:
1. Add new methods to existing class
2. Modify the existing features. It is called
Overriding Methods.
31
Overriding Methods (3)
• Overriding method is a technique to modify a method in the
superclass.
• Overriding method is a method, defined in subclass, which
has the same name and return type to a method in
superclass.
For example:
- The Circle has findArea() but Cylinder doesn’t has it. If we call
findArea(), it is always the Circle’s.
- But the cylinder can have findArea() for itself. This implementation
is called overriding method.
32
Overriding Methods (3)
• Please look at the code on page 292, Listing 8.2.
33
Important Note (1)
1. In the subclass, we can invoke accessible things, e.g. public
methods or constructor, from the superclass. E.g.:
- After a class inherits JFrame, then we can call setTitle(), setSize(),
setVisible() etc.
2. In a constructor of subclass, the non-arg constructor of the
superclass is ALWAYS invoked. Let see slide “Important Note (2)”.
3. A subclass can NEVER inherit a superclass which has no
non-arg constructor. Let see slide “Important Note (3)”.
34
Important Note (2)
//Circle class
public class Circle{
private double radius;
public Circle(){ // non-arg constructor
radius = 5;
}
public double findArea(){
return radius * radius * 3.14;
}
}
//TestCircle class
public class TestCircle extends Circle {
public static void main(String[] args){
TestCircle tc = new TestCircle();
System.out.println(tc.findArea());//output: 78.5
}
}
35
Important Note (3)
//Circle class
public class Circle{
private double radius;
//It doesn’t have non-arg constructor Here
public Circle(double radius){
this.radius = radius;
}
public double findArea(){
return radius * radius * 3.14;
}
}
//TestCircle class
public class TestCircle extends Circle {
public static void main(String[] args){
}
}
36
cannot find symbol
symbol: constructor Circle()
location: class Circle
1 error
The Object class
37
The Object class (1)
• public boolean equals(Object object)
Indicates whether a object is "equal to" this one. E.g.:
Circle c1 = new Circle();
if(c1.equals(c1)){
}
Note: We have to override it to test our comparison.
• public int hashCode()
Returns a hash code value for the object. see “Java
Collection Framework.”
38
The Object class (2)
• public String toString()
Return a string that represents the object. e.g.
Circle c1 = new Circle();
c1.toString();
//output: Circle@24efe3
Note: We have to override it to display our wise.
39

More Related Content

What's hot (20)

11. java methods
11. java methods11. java methods
11. java methods
M H Buddhika Ariyaratne
 
Java basic
Java basicJava basic
Java basic
Sonam Sharma
 
Server-side JS with NodeJS
Server-side JS with NodeJSServer-side JS with NodeJS
Server-side JS with NodeJS
Lilia Sfaxi
 
Deep dive into Vue.js
Deep dive into Vue.jsDeep dive into Vue.js
Deep dive into Vue.js
선협 이
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
Java Lover
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
Nilesh Dalvi
 
Introduction of java
Introduction  of javaIntroduction  of java
Introduction of java
Madishetty Prathibha
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
Arnab Bhaumik
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
Manav Prasad
 
Nouveautés de java 8
Nouveautés de java 8Nouveautés de java 8
Nouveautés de java 8
Florian Beaufumé
 
Android Accessibility
Android AccessibilityAndroid Accessibility
Android Accessibility
Ascii Huang
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
Drishti Bhalla
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
Hitesh-Java
 
MongoDB 이해하기
MongoDB 이해하기MongoDB 이해하기
MongoDB 이해하기
선협 이
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
Sandeep Rawat
 
JAVA PPT by NAVEEN TOKAS
JAVA PPT by NAVEEN TOKASJAVA PPT by NAVEEN TOKAS
JAVA PPT by NAVEEN TOKAS
NAVEEN TOKAS
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
Garrett Welson
 
Java servlets
Java servletsJava servlets
Java servlets
Mukesh Tekwani
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
Hitesh-Java
 
Javascript
JavascriptJavascript
Javascript
Rajavel Dhandabani
 

Viewers also liked (20)

Objected-Oriented Programming with Java
Objected-Oriented Programming with JavaObjected-Oriented Programming with Java
Objected-Oriented Programming with Java
Oum Saokosal
 
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NF
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NFDatabase Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NF
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NF
Oum Saokosal
 
10.3 Android Video
10.3 Android Video10.3 Android Video
10.3 Android Video
Oum Saokosal
 
11.1 Android with HTML
11.1 Android with HTML11.1 Android with HTML
11.1 Android with HTML
Oum Saokosal
 
Java Programming - Introduction to Abstract Class
Java Programming - Introduction to Abstract ClassJava Programming - Introduction to Abstract Class
Java Programming - Introduction to Abstract Class
Oum Saokosal
 
04. Review OOP with Java
04. Review OOP with Java04. Review OOP with Java
04. Review OOP with Java
Oum Saokosal
 
Database Concept - ERD Mapping to MS Access
Database Concept - ERD Mapping to MS AccessDatabase Concept - ERD Mapping to MS Access
Database Concept - ERD Mapping to MS Access
Oum Saokosal
 
Inheritance, Object Oriented Programming
Inheritance, Object Oriented ProgrammingInheritance, Object Oriented Programming
Inheritance, Object Oriented Programming
Arslan Waseem
 
09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)
Oum Saokosal
 
Database Concept - Normalization (1NF, 2NF, 3NF)
Database Concept - Normalization (1NF, 2NF, 3NF)Database Concept - Normalization (1NF, 2NF, 3NF)
Database Concept - Normalization (1NF, 2NF, 3NF)
Oum Saokosal
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and Interface
Oum Saokosal
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
Tareq Hasan
 
Inheritance
InheritanceInheritance
Inheritance
Sapna Sharma
 
Chapter 12
Chapter 12Chapter 12
Chapter 12
Terry Yoast
 
Android - Introduction
Android - IntroductionAndroid - Introduction
Android - Introduction
Oum Saokosal
 
Object Oriended Programming with Java
Object Oriended Programming with JavaObject Oriended Programming with Java
Object Oriended Programming with Java
Jakir Hossain
 
10.1. Android Audio
10.1. Android Audio10.1. Android Audio
10.1. Android Audio
Oum Saokosal
 
07.4. Android Basic Simple Browser (WebView)
07.4. Android Basic Simple Browser (WebView)07.4. Android Basic Simple Browser (WebView)
07.4. Android Basic Simple Browser (WebView)
Oum Saokosal
 
06. Android Basic Widget and Container
06. Android Basic Widget and Container06. Android Basic Widget and Container
06. Android Basic Widget and Container
Oum Saokosal
 
07.3. Android Alert message, List, Dropdown, and Auto Complete
07.3. Android Alert message, List, Dropdown, and Auto Complete07.3. Android Alert message, List, Dropdown, and Auto Complete
07.3. Android Alert message, List, Dropdown, and Auto Complete
Oum Saokosal
 
Objected-Oriented Programming with Java
Objected-Oriented Programming with JavaObjected-Oriented Programming with Java
Objected-Oriented Programming with Java
Oum Saokosal
 
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NF
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NFDatabase Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NF
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NF
Oum Saokosal
 
10.3 Android Video
10.3 Android Video10.3 Android Video
10.3 Android Video
Oum Saokosal
 
11.1 Android with HTML
11.1 Android with HTML11.1 Android with HTML
11.1 Android with HTML
Oum Saokosal
 
Java Programming - Introduction to Abstract Class
Java Programming - Introduction to Abstract ClassJava Programming - Introduction to Abstract Class
Java Programming - Introduction to Abstract Class
Oum Saokosal
 
04. Review OOP with Java
04. Review OOP with Java04. Review OOP with Java
04. Review OOP with Java
Oum Saokosal
 
Database Concept - ERD Mapping to MS Access
Database Concept - ERD Mapping to MS AccessDatabase Concept - ERD Mapping to MS Access
Database Concept - ERD Mapping to MS Access
Oum Saokosal
 
Inheritance, Object Oriented Programming
Inheritance, Object Oriented ProgrammingInheritance, Object Oriented Programming
Inheritance, Object Oriented Programming
Arslan Waseem
 
09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)
Oum Saokosal
 
Database Concept - Normalization (1NF, 2NF, 3NF)
Database Concept - Normalization (1NF, 2NF, 3NF)Database Concept - Normalization (1NF, 2NF, 3NF)
Database Concept - Normalization (1NF, 2NF, 3NF)
Oum Saokosal
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and Interface
Oum Saokosal
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
Tareq Hasan
 
Android - Introduction
Android - IntroductionAndroid - Introduction
Android - Introduction
Oum Saokosal
 
Object Oriended Programming with Java
Object Oriended Programming with JavaObject Oriended Programming with Java
Object Oriended Programming with Java
Jakir Hossain
 
10.1. Android Audio
10.1. Android Audio10.1. Android Audio
10.1. Android Audio
Oum Saokosal
 
07.4. Android Basic Simple Browser (WebView)
07.4. Android Basic Simple Browser (WebView)07.4. Android Basic Simple Browser (WebView)
07.4. Android Basic Simple Browser (WebView)
Oum Saokosal
 
06. Android Basic Widget and Container
06. Android Basic Widget and Container06. Android Basic Widget and Container
06. Android Basic Widget and Container
Oum Saokosal
 
07.3. Android Alert message, List, Dropdown, and Auto Complete
07.3. Android Alert message, List, Dropdown, and Auto Complete07.3. Android Alert message, List, Dropdown, and Auto Complete
07.3. Android Alert message, List, Dropdown, and Auto Complete
Oum Saokosal
 
Ad

Similar to Java Programming - Inheritance (20)

Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
OUM SAOKOSAL
 
Unit 2
Unit 2Unit 2
Unit 2
Amar Jukuntla
 
RajLec10.ppt
RajLec10.pptRajLec10.ppt
RajLec10.ppt
Rassjb
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
HarshithaAllu
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
Kuntal Bhowmick
 
Chap3 inheritance
Chap3 inheritanceChap3 inheritance
Chap3 inheritance
raksharao
 
M251_Meeting 5 (Inheritance and Polymorphism).ppt
M251_Meeting 5 (Inheritance and Polymorphism).pptM251_Meeting 5 (Inheritance and Polymorphism).ppt
M251_Meeting 5 (Inheritance and Polymorphism).ppt
smartashammari
 
inheritance and interface in oops with java .pptx
inheritance and interface in oops with java .pptxinheritance and interface in oops with java .pptx
inheritance and interface in oops with java .pptx
janetvidyaanancys
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
Lokesh Kakkar Mobile No. 814-614-5674
 
Core java complete notes - PAID call at +91-814-614-5674
Core java complete notes - PAID call at +91-814-614-5674Core java complete notes - PAID call at +91-814-614-5674
Core java complete notes - PAID call at +91-814-614-5674
WebKrit Infocom
 
Java programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- InheritanceJava programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- Inheritance
Jyothishmathi Institute of Technology and Science Karimnagar
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interface
Shubham Sharma
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
COMSATS Institute of Information Technology
 
10. inheritance
10. inheritance10. inheritance
10. inheritance
M H Buddhika Ariyaratne
 
Object and class
Object and classObject and class
Object and class
mohit tripathi
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
GaneshKumarKanthiah
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
PRN USM
 
Modules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptxModules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
OUM SAOKOSAL
 
RajLec10.ppt
RajLec10.pptRajLec10.ppt
RajLec10.ppt
Rassjb
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
Kuntal Bhowmick
 
Chap3 inheritance
Chap3 inheritanceChap3 inheritance
Chap3 inheritance
raksharao
 
M251_Meeting 5 (Inheritance and Polymorphism).ppt
M251_Meeting 5 (Inheritance and Polymorphism).pptM251_Meeting 5 (Inheritance and Polymorphism).ppt
M251_Meeting 5 (Inheritance and Polymorphism).ppt
smartashammari
 
inheritance and interface in oops with java .pptx
inheritance and interface in oops with java .pptxinheritance and interface in oops with java .pptx
inheritance and interface in oops with java .pptx
janetvidyaanancys
 
Core java complete notes - PAID call at +91-814-614-5674
Core java complete notes - PAID call at +91-814-614-5674Core java complete notes - PAID call at +91-814-614-5674
Core java complete notes - PAID call at +91-814-614-5674
WebKrit Infocom
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interface
Shubham Sharma
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
PRN USM
 
Modules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptxModules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
Ad

More from Oum Saokosal (9)

12. Android Basic Google Map
12. Android Basic Google Map12. Android Basic Google Map
12. Android Basic Google Map
Oum Saokosal
 
10.2 Android Audio with SD Card
10.2 Android Audio with SD Card10.2 Android Audio with SD Card
10.2 Android Audio with SD Card
Oum Saokosal
 
08.1. Android How to Use Intent (explicit)
08.1. Android How to Use Intent (explicit)08.1. Android How to Use Intent (explicit)
08.1. Android How to Use Intent (explicit)
Oum Saokosal
 
07.1. Android Even Handling
07.1. Android Even Handling07.1. Android Even Handling
07.1. Android Even Handling
Oum Saokosal
 
More on Application Structure
More on Application StructureMore on Application Structure
More on Application Structure
Oum Saokosal
 
Basic Understanding of Android XML
Basic Understanding of Android XMLBasic Understanding of Android XML
Basic Understanding of Android XML
Oum Saokosal
 
02.1 - Getting Started with Android
02.1 - Getting Started with Android02.1 - Getting Started with Android
02.1 - Getting Started with Android
Oum Saokosal
 
Introduction to Android
Introduction to AndroidIntroduction to Android
Introduction to Android
Oum Saokosal
 
Using intents in android
Using intents in androidUsing intents in android
Using intents in android
Oum Saokosal
 
12. Android Basic Google Map
12. Android Basic Google Map12. Android Basic Google Map
12. Android Basic Google Map
Oum Saokosal
 
10.2 Android Audio with SD Card
10.2 Android Audio with SD Card10.2 Android Audio with SD Card
10.2 Android Audio with SD Card
Oum Saokosal
 
08.1. Android How to Use Intent (explicit)
08.1. Android How to Use Intent (explicit)08.1. Android How to Use Intent (explicit)
08.1. Android How to Use Intent (explicit)
Oum Saokosal
 
07.1. Android Even Handling
07.1. Android Even Handling07.1. Android Even Handling
07.1. Android Even Handling
Oum Saokosal
 
More on Application Structure
More on Application StructureMore on Application Structure
More on Application Structure
Oum Saokosal
 
Basic Understanding of Android XML
Basic Understanding of Android XMLBasic Understanding of Android XML
Basic Understanding of Android XML
Oum Saokosal
 
02.1 - Getting Started with Android
02.1 - Getting Started with Android02.1 - Getting Started with Android
02.1 - Getting Started with Android
Oum Saokosal
 
Introduction to Android
Introduction to AndroidIntroduction to Android
Introduction to Android
Oum Saokosal
 
Using intents in android
Using intents in androidUsing intents in android
Using intents in android
Oum Saokosal
 

Recently uploaded (20)

Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 

Java Programming - Inheritance

  • 1. Chapter 8 Inheritance and Polymorphism Oum Saokosal, Chief of Computer Science National Polytechnic Institute of Cambodia Tel: (855)-12-252-752 E-mail: [email protected] 1
  • 3. Inheritance 1. What is Inheritance? 2. Why Inheritance? 3. How to use it? 4. Superclass & Subclass 5. Using keyword super 6. Overriding Methods 7. The Object class 3
  • 4. 1. What is Inheritance? 4
  • 5. 1. What is Inheritance? (1) • OOP has 3 features: 1. Class Encapsulation 2. Inheritance 3. Polymorphism • OOP allows you to derive (create) new objects from existing classes. E.g. – You can create objects from a class: • Circle cir = new Circle(); • Word w = new Word(“N P I C”); 5
  • 6. 1. What is Inheritance? (2) • But OOP has other mechanisms. One of them is called Inheritance. • Inheritance is a mechanism to make classes inherit properties/methods from an existing class. • Inherit (v) ¬TTYlekrþtMENl¦ • Inheritance (n) receiving properties 6
  • 7. 1. What is Inheritance? (3) • In fact, every class in Java is always inherited from an existing class, either explicitly or implicitly. • In Java, every class is inherited from java.lang.Object. To be clear, please look at an example at next slide. 7
  • 8. 1. What is Inheritance? (4) - Example 1. Please create a blank class, say, BlankSample public class BlankSample { } 1. Then create a test class, say, TestBlank public class TestBlank { public static void main(String[] args){ BlankSample bs = new BlankSample(); System.out.print(bs.toString()); } } The question is why we can call bs.toString()? If we look at BlankSample, there is toString(). Why? 8
  • 9. 1. What is Inheritance? (5) - IDE 9
  • 10. 1. What is Inheritance? (6) • Where these methods come from? They are from java.lang.Object. Because every class in Java inherits from java.lang.Object. • To be sure, please look at the API and find out java.lang.Object. Then see its methods. – clone(), equals(Object obj), finalize(), getClass(), hashCode(), notify(), notifyAll(), toString() and wait() 10
  • 12. 2. Why Inheritance? • Classes often share capabilities • We want to avoid re-coding these capabilities • Reuse of these would be best to – Improve maintainability – Reduce cost – Improve “real world” modeling 12
  • 13. 2. Why Inheritance? -Benefits • No need to reinvent the wheel. • Allows us to build on existing codes without having to copy it and past it or rewrite it again, etc. • To create the subclass, we need to program only the differences between the superclass and the subclass that inherits from it. • Make class more flexible. 13
  • 14. 3. How to use it? 14
  • 15. 3. How to use it? (1) • In Java, to enable a class inherit an existing class, we have to use a keyword “extends”. For example, we have Circle class: public class Circle{ private double radius; public Circle(){} public Circle(double radius){ this.radius = radius; } public void setRadius(double radius){ this.radius = radius; } public double findArea(){ return radius * radius *3.14; } } 15
  • 16. 3. How to use it? (2) • Then we want another class, say, TestCircle, inherits from the Circle class. public class TestCircle extends Circle{ public static void main(String[] args){ TestCircle tc1 = new TestCircle(); tc1.setRadius(5.0); System.out.println(tc1.findArea()); } } • Please note that TestCircle didn’t define setRadius() and getArea() methods but it could use the methods. • The reason is TestCircle inherits from Circle class. 16
  • 17. 3. How to use it? – Note (1) • Usually inheritance is used to improve features of an existing class. • Please look at the code on page 288, listing 8.1 First Version of the Cylinder class. – The Circle has already the findArea() – So the formula to find Cylinder’s Volume is : volume = Area * length 17
  • 18. 3. How to use it? – Note (2) public class Cylinder extends Circle { private double length = 1; public double getLength(){ return length; } public void setLength(double length){ this.length = length; } public double findVolume(){ return findArea() * length; } } 18
  • 19. 3. How to use it? – Note (3) public class TestCylinder { public static void main(String[] args){ Cylinder c1 = new Cylinder(); c1.setRadius(2.5); // from Circle c1.setLength(5); // from Cylinder System.out.println(c1.findVolume()); } } • Please note that the cylinder’s object, c1, could call a method, “setLength()”, from Cylinder class and also could call a method, “setRadius()”, from Circle class. 19
  • 20. 4. Superclass & Subclass 20
  • 21. 4. Superclass & Subclass (1) • The cylinder class inherits features from circle class. Then, – Cylinder is subclass – Circle is superclass Super inherit Subclass 21 Circle Cylinder
  • 22. 4. Superclass & Subclass (2) Quick Check: C1 <- C2 <- C3 <- C4 What are superclass and subclass? - C1 is the superclass of C2, C3, & C4 - C2 are the subclass of C1 and the superclass of C3 & C4 - C3 are the subclass of C1 & C2 and the superclass of C4 - C4 is the subclass of C1, C2 & C3 • It means if we call the final subclass, e.g. C4, then we can use features from C1, C2, C3, and, of course, C4 itself. 22
  • 23. 4. Superclass & Subclass (3) – Java API • Please check API Documentation: Javax.swing.JFrame is the subclass of Frame,Window,Container,Component,Object. So if we use JFrame, it means we use features from all of the superclasses. 23
  • 24. 4. Superclass & Subclass (4) • Sample of using JFrame import javax.swing.*; public class TestJFrame extends JFrame { public static void main(String[] args){ TestJFrame frame = new TestJFrame(); frame.setTitle("Hi I am JFrame"); frame.setSize(400,300); frame.setVisible(true); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); } } // Note the underline codes 24
  • 25. 5. Using keyword super 25
  • 26. 5. Using keyword super (1) • super is used to call: 1. Constructors of the superclass 2. Methods of the superclass 26
  • 27. Using keyword super (2) • To call constructors of the superclass super(); //call no-arg constructor super(5.0); //call arg constructor • Note super(): 1. MUST be written in the 1st line of subclass constructors 2. Cannot be written in other methods 3. Is the only way to call superclass constructor. 27
  • 28. Using keyword super (3) • To call methods of the superclass super.setRadius(5); // setRadius(5); super.findArea(); super.toString(); Note: • This keyword is not always used to call methods from superclass. • We can call superclass methods by calling directly the methods name. Please look at slide # 14. • However, super is used not to confuse with the name of the overriding methods. 28
  • 30. Overriding Methods (1) In the real world: • Researchers sometimes never invent or find a new thing. In fact, they just improve an existing thing. • To improve the thing, they just: 1. Add new features 2. Modify existing features. 30
  • 31. Overriding Methods (2) In OOP: It is true to the both things above. The inheritance helps us to do these. We can: 1. Add new methods to existing class 2. Modify the existing features. It is called Overriding Methods. 31
  • 32. Overriding Methods (3) • Overriding method is a technique to modify a method in the superclass. • Overriding method is a method, defined in subclass, which has the same name and return type to a method in superclass. For example: - The Circle has findArea() but Cylinder doesn’t has it. If we call findArea(), it is always the Circle’s. - But the cylinder can have findArea() for itself. This implementation is called overriding method. 32
  • 33. Overriding Methods (3) • Please look at the code on page 292, Listing 8.2. 33
  • 34. Important Note (1) 1. In the subclass, we can invoke accessible things, e.g. public methods or constructor, from the superclass. E.g.: - After a class inherits JFrame, then we can call setTitle(), setSize(), setVisible() etc. 2. In a constructor of subclass, the non-arg constructor of the superclass is ALWAYS invoked. Let see slide “Important Note (2)”. 3. A subclass can NEVER inherit a superclass which has no non-arg constructor. Let see slide “Important Note (3)”. 34
  • 35. Important Note (2) //Circle class public class Circle{ private double radius; public Circle(){ // non-arg constructor radius = 5; } public double findArea(){ return radius * radius * 3.14; } } //TestCircle class public class TestCircle extends Circle { public static void main(String[] args){ TestCircle tc = new TestCircle(); System.out.println(tc.findArea());//output: 78.5 } } 35
  • 36. Important Note (3) //Circle class public class Circle{ private double radius; //It doesn’t have non-arg constructor Here public Circle(double radius){ this.radius = radius; } public double findArea(){ return radius * radius * 3.14; } } //TestCircle class public class TestCircle extends Circle { public static void main(String[] args){ } } 36 cannot find symbol symbol: constructor Circle() location: class Circle 1 error
  • 38. The Object class (1) • public boolean equals(Object object) Indicates whether a object is "equal to" this one. E.g.: Circle c1 = new Circle(); if(c1.equals(c1)){ } Note: We have to override it to test our comparison. • public int hashCode() Returns a hash code value for the object. see “Java Collection Framework.” 38
  • 39. The Object class (2) • public String toString() Return a string that represents the object. e.g. Circle c1 = new Circle(); c1.toString(); //output: Circle@24efe3 Note: We have to override it to display our wise. 39