SlideShare a Scribd company logo
Chapter 8 Inheritance and Polymorphism Oum Saokosal , Head of IT Department National Polytechnic Institute of Cambodia Tel: (855)-12-417214 E-mail: oum_saokosal@yahoo.com
Inheritance Chapter 8 Inheritance and Polymorphism
Inheritance What is Inheritance? Why Inheritance? How to use it? Superclass & Subclass Using keyword  super Overriding Methods The  Object  class
1. What is Inheritance?
1. What is Inheritance? (1) OOP has 3 features: Class Encapsulation  Inheritance 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”);
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
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.
1. What is Inheritance? (4) - Example Please create a blank class, say, BlankSample public class BlankSample { } 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?
1. What is Inheritance? (5) - IDE
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()
2. Why Inheritance?
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
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.
3. How to use it?
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; } }
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.
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
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; } }
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.
4. Superclass & Subclass
4. Superclass & Subclass (1) The  cylinder  class inherits features from  circle  class. Then, Cylinder is  subclass Circle is  superclass Super   inherit  Subclass 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.
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.
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 ( &quot;Hi I am JFrame&quot; ); frame .setSize (400,300); frame .setVisible ( true );   frame .setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE); } }  // Note the underline codes
5. Using keyword  super
5. Using keyword  super  (1) super  is used to call: Constructors of the superclass Methods of the superclass
Using keyword  super  (2) To call constructors of the superclass super(); //call no-arg constructor super(5.0); //call arg constructor Note super() : MUST be written in the 1 st  line of subclass constructors Cannot be written in other methods Is the only way to call superclass constructor.
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.
6. Overriding Methods
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: Add new features Modify existing features.
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 .
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.
Overriding Methods (3) Please look at the code on page 292, Listing 8.2.
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. 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)”.
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; } } //Test Circle class public class  TestCircle  extends  Circle { public static void  main( String [] args){ TestCircle tc =  new  TestCircle(); System .out.println(tc.findArea()); //output: 78.5 } }
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 ; } } //Test Circle class public class  TestCircle  extends  Circle { public static void  main( String [] args){ } } cannot find symbol symbol: constructor Circle() location: class Circle 1 error
The  Object  class
The  Object  class (1) public boolean equals(Object object) Indicates whether a object is &quot;equal to&quot; 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.”
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.

More Related Content

Viewers also liked (20)

PPT
Actionscript 3 - Session 7 Other Note
OUM SAOKOSAL
 
PPT
Actionscript 3 - Session 5 The Display Api And The Display List
OUM SAOKOSAL
 
PPT
Actionscript 3 - Session 6 Interactivity
OUM SAOKOSAL
 
PPT
SkillsMatter - In-the-Brain session - What's new in ActionScript 3.0
Peter Elst
 
PPT
Actionscript 3 - Session 3 Action Script And Flash
OUM SAOKOSAL
 
PPT
Actionscript 3 - Session 1 Introduction To As 3
OUM SAOKOSAL
 
PPTX
EXAMEN PRÁCTICO DE COMPUTACIÓN 2DO BIM
allisonnicole97
 
DOCX
Convocatorias de personal (17 nov-10)
El Rincon de la Faceac
 
PPT
FRAS4 EVOLVO. La Re-Evaluación del Estrés Oxidativo en la Cavidad Oral
Biozone Europa
 
DOCX
Dfso proyecto amy zahory ruiz hernandez - dariana ariday cruz ocampo - samue...
Amy Hernandez
 
PDF
EU Space Research Program @ Stanford - Reinhard Schulte-Braucks - 21 July 2010
Burton Lee
 
PDF
Kinderzeitung Oktober2009
ADTECH / AOL Platforms
 
PDF
Nuevos escenarios
Jorge Alberto Hidalgo Toledo
 
DOCX
Incoterms
Salomón Valdez
 
PPT
Cuerpo de Cuardacostas - COGUAR
Luis Pacheco
 
PDF
Programa Escenium 2010
ESCENIUM
 
PDF
8_Diversity and antimicrobial activity of fungal endophyte communities associ...
Aline Bruna Martins Vaz
 
PPT
Balbuzie stato dell'arte. D.ssa Angela SCALZO
Rosangela Scalzo
 
PDF
socialmedia@cubet
Diana Philip
 
PDF
Action Script
Angelin R
 
Actionscript 3 - Session 7 Other Note
OUM SAOKOSAL
 
Actionscript 3 - Session 5 The Display Api And The Display List
OUM SAOKOSAL
 
Actionscript 3 - Session 6 Interactivity
OUM SAOKOSAL
 
SkillsMatter - In-the-Brain session - What's new in ActionScript 3.0
Peter Elst
 
Actionscript 3 - Session 3 Action Script And Flash
OUM SAOKOSAL
 
Actionscript 3 - Session 1 Introduction To As 3
OUM SAOKOSAL
 
EXAMEN PRÁCTICO DE COMPUTACIÓN 2DO BIM
allisonnicole97
 
Convocatorias de personal (17 nov-10)
El Rincon de la Faceac
 
FRAS4 EVOLVO. La Re-Evaluación del Estrés Oxidativo en la Cavidad Oral
Biozone Europa
 
Dfso proyecto amy zahory ruiz hernandez - dariana ariday cruz ocampo - samue...
Amy Hernandez
 
EU Space Research Program @ Stanford - Reinhard Schulte-Braucks - 21 July 2010
Burton Lee
 
Kinderzeitung Oktober2009
ADTECH / AOL Platforms
 
Nuevos escenarios
Jorge Alberto Hidalgo Toledo
 
Incoterms
Salomón Valdez
 
Cuerpo de Cuardacostas - COGUAR
Luis Pacheco
 
Programa Escenium 2010
ESCENIUM
 
8_Diversity and antimicrobial activity of fungal endophyte communities associ...
Aline Bruna Martins Vaz
 
Balbuzie stato dell'arte. D.ssa Angela SCALZO
Rosangela Scalzo
 
socialmedia@cubet
Diana Philip
 
Action Script
Angelin R
 

Similar to Chapter 8 Inheritance (20)

PPT
Java Programming - Inheritance
Oum Saokosal
 
PDF
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL
 
PPTX
Ch5 inheritance
HarshithaAllu
 
PPT
RajLec10.ppt
Rassjb
 
PDF
Unit 2
Amar Jukuntla
 
PPTX
Chap3 inheritance
raksharao
 
PPT
M251_Meeting 5 (Inheritance and Polymorphism).ppt
smartashammari
 
PPTX
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
DOCX
Class notes(week 6) on inheritance and multiple inheritance
Kuntal Bhowmick
 
PPTX
10. inheritance
M H Buddhika Ariyaratne
 
PPT
Object and class
mohit tripathi
 
PPT
Java inheritance
GaneshKumarKanthiah
 
PDF
Chapter 04 inheritance
Nurhanna Aziz
 
PPT
Inheritance & Polymorphism - 1
PRN USM
 
PPTX
inheritance and interface in oops with java .pptx
janetvidyaanancys
 
PPT
Chap11
Terry Yoast
 
PPT
7_-_Inheritance
Krishna Sujeer
 
PPT
9781439035665 ppt ch10
Terry Yoast
 
PPTX
‫Chapter3 inheritance
Mahmoud Alfarra
 
PPTX
Inheritance in java
Tech_MX
 
Java Programming - Inheritance
Oum Saokosal
 
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL
 
Ch5 inheritance
HarshithaAllu
 
RajLec10.ppt
Rassjb
 
Chap3 inheritance
raksharao
 
M251_Meeting 5 (Inheritance and Polymorphism).ppt
smartashammari
 
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
Class notes(week 6) on inheritance and multiple inheritance
Kuntal Bhowmick
 
10. inheritance
M H Buddhika Ariyaratne
 
Object and class
mohit tripathi
 
Java inheritance
GaneshKumarKanthiah
 
Chapter 04 inheritance
Nurhanna Aziz
 
Inheritance & Polymorphism - 1
PRN USM
 
inheritance and interface in oops with java .pptx
janetvidyaanancys
 
Chap11
Terry Yoast
 
7_-_Inheritance
Krishna Sujeer
 
9781439035665 ppt ch10
Terry Yoast
 
‫Chapter3 inheritance
Mahmoud Alfarra
 
Inheritance in java
Tech_MX
 
Ad

More from OUM SAOKOSAL (20)

PPTX
Class Diagram | OOP and Design Patterns by Oum Saokosal
OUM SAOKOSAL
 
PPTX
Android app development - Java Programming for Android
OUM SAOKOSAL
 
PDF
Java OOP Programming language (Part 8) - Java Database JDBC
OUM SAOKOSAL
 
PDF
Java OOP Programming language (Part 7) - Swing
OUM SAOKOSAL
 
PDF
Java OOP Programming language (Part 6) - Abstract Class & Interface
OUM SAOKOSAL
 
PDF
Java OOP Programming language (Part 4) - Collection
OUM SAOKOSAL
 
PDF
Java OOP Programming language (Part 3) - Class and Object
OUM SAOKOSAL
 
PDF
Java OOP Programming language (Part 1) - Introduction to Java
OUM SAOKOSAL
 
PDF
Javascript & DOM - Part 1- Javascript Tutorial for Beginners with Examples
OUM SAOKOSAL
 
PDF
Aggregate rank bringing order to web sites
OUM SAOKOSAL
 
DOC
How to succeed in graduate school
OUM SAOKOSAL
 
PDF
Google
OUM SAOKOSAL
 
PDF
E miner
OUM SAOKOSAL
 
PDF
Data preparation for mining world wide web browsing patterns (1999)
OUM SAOKOSAL
 
PDF
Consumer acceptance of online banking an extension of the technology accepta...
OUM SAOKOSAL
 
DOCX
When Do People Help
OUM SAOKOSAL
 
DOC
Mc Nemar
OUM SAOKOSAL
 
DOCX
Correlation Example
OUM SAOKOSAL
 
DOC
Sem Ski Amos
OUM SAOKOSAL
 
PPT
Sem+Essentials
OUM SAOKOSAL
 
Class Diagram | OOP and Design Patterns by Oum Saokosal
OUM SAOKOSAL
 
Android app development - Java Programming for Android
OUM SAOKOSAL
 
Java OOP Programming language (Part 8) - Java Database JDBC
OUM SAOKOSAL
 
Java OOP Programming language (Part 7) - Swing
OUM SAOKOSAL
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
OUM SAOKOSAL
 
Java OOP Programming language (Part 4) - Collection
OUM SAOKOSAL
 
Java OOP Programming language (Part 3) - Class and Object
OUM SAOKOSAL
 
Java OOP Programming language (Part 1) - Introduction to Java
OUM SAOKOSAL
 
Javascript & DOM - Part 1- Javascript Tutorial for Beginners with Examples
OUM SAOKOSAL
 
Aggregate rank bringing order to web sites
OUM SAOKOSAL
 
How to succeed in graduate school
OUM SAOKOSAL
 
Google
OUM SAOKOSAL
 
E miner
OUM SAOKOSAL
 
Data preparation for mining world wide web browsing patterns (1999)
OUM SAOKOSAL
 
Consumer acceptance of online banking an extension of the technology accepta...
OUM SAOKOSAL
 
When Do People Help
OUM SAOKOSAL
 
Mc Nemar
OUM SAOKOSAL
 
Correlation Example
OUM SAOKOSAL
 
Sem Ski Amos
OUM SAOKOSAL
 
Sem+Essentials
OUM SAOKOSAL
 
Ad

Recently uploaded (20)

PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Advancing WebDriver BiDi support in WebKit
Igalia
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
July Patch Tuesday
Ivanti
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Advancing WebDriver BiDi support in WebKit
Igalia
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
July Patch Tuesday
Ivanti
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 

Chapter 8 Inheritance

  • 1. Chapter 8 Inheritance and Polymorphism Oum Saokosal , Head of IT Department National Polytechnic Institute of Cambodia Tel: (855)-12-417214 E-mail: [email protected]
  • 2. Inheritance Chapter 8 Inheritance and Polymorphism
  • 3. Inheritance What is Inheritance? Why Inheritance? How to use it? Superclass & Subclass Using keyword super Overriding Methods The Object class
  • 4. 1. What is Inheritance?
  • 5. 1. What is Inheritance? (1) OOP has 3 features: Class Encapsulation Inheritance 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”);
  • 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
  • 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.
  • 8. 1. What is Inheritance? (4) - Example Please create a blank class, say, BlankSample public class BlankSample { } 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?
  • 9. 1. What is Inheritance? (5) - IDE
  • 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()
  • 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
  • 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.
  • 14. 3. How to use it?
  • 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; } }
  • 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.
  • 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
  • 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; } }
  • 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.
  • 20. 4. Superclass & Subclass
  • 21. 4. Superclass & Subclass (1) The cylinder class inherits features from circle class. Then, Cylinder is subclass Circle is superclass Super inherit Subclass 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.
  • 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.
  • 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 ( &quot;Hi I am JFrame&quot; ); frame .setSize (400,300); frame .setVisible ( true ); frame .setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE); } } // Note the underline codes
  • 26. 5. Using keyword super (1) super is used to call: Constructors of the superclass Methods of the superclass
  • 27. Using keyword super (2) To call constructors of the superclass super(); //call no-arg constructor super(5.0); //call arg constructor Note super() : MUST be written in the 1 st line of subclass constructors Cannot be written in other methods Is the only way to call superclass constructor.
  • 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.
  • 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: Add new features Modify existing features.
  • 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 .
  • 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.
  • 33. Overriding Methods (3) Please look at the code on page 292, Listing 8.2.
  • 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. 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)”.
  • 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; } } //Test Circle class public class TestCircle extends Circle { public static void main( String [] args){ TestCircle tc = new TestCircle(); System .out.println(tc.findArea()); //output: 78.5 } }
  • 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 ; } } //Test Circle class public class TestCircle extends Circle { public static void main( String [] args){ } } cannot find symbol symbol: constructor Circle() location: class Circle 1 error
  • 37. The Object class
  • 38. The Object class (1) public boolean equals(Object object) Indicates whether a object is &quot;equal to&quot; 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.”
  • 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.