SlideShare a Scribd company logo
1 of 24
Programming in Java
5-day workshop
OOP Inheritance
Matt Collison
JP Morgan Chase 2021
PiJ3.1: OOP Inheritance
Four principles of OOP:
1.Encapsulation – defining a class
2.Abstraction – modifying the objects
3.Inheritance – extending classes
4.Polymorphism – implementing interfaces
How do we achieve inheritance through
OOP?
• Classes and objects: The first order of abstraction. class new
• There are lots of things that the same but with different attribute values.
• For example people – we all have a name, a height, we have interests and friends. Think of a
social media platform. Everyone has a profile but everyone’s profile is unique.
• Class inheritance: The second order of abstraction extends super instanceof
• The definitions for things can share common features.
• For example the administrator account and a user account both require a username,
password and contact details. Each of these account would extend a common ‘parent’
account definition.
• Polymorphism: The third order of abstraction implements
• The definitions for things can share features but complete them in different ways to achieve
different behaviours. For example an e-commerce store must have a database binding, a
layout schema for the UI but the specific implementations are unique. These aren’t just
different values but different functions.
Inheritance
public class Identifier extends
ParentClassIdentifier{
• All subclasses inherit:
• Attributes – access to fields to describe the class
• Constructors – access to methods to create the object
• Methods – access to functions to describe the objects behaviour
Assuming typical access modifiers
…except attributes – why?
Inheritance
• Superclass or base, parent class
• Subclass or derived, child, extended class
• Single inheritance only – there can only be one superclass for each
class. This creates a hierarchy or tree.
Shapes
public Shape {
//What goes in here?
}
public Triangle extends Shape {
//What goes in here?
}
Method overriding – access modifiers
Access modifier within class within package global but subclass global
private Yes No No No
default Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes
What can a subclass do?
• A subclass can also add its own attributes and methods.
• add same-signature methods - method overriding.
• add same-name attributes (but not recommended) - attribute hiding.
Q: Can anyone give an example of additional functionality you might
implement in subclass?
Method overriding
• Method overriding: A subclass defines a method which has the same
name, number and type of parameters, and return type as a method
in the superclass.
• NOTE:
• Recall Method overloading: If a class has multiple methods having the same
name but different in parameters.
• When overriding a method, it is recommended to use the @Override
annotation, though it is optional.
Example – write a class for Animal
// A demo for inheritance class
public class Animal{
// two common attributes for all animals
private String color;
private int age;
// two common methods for all animals
public void eat(){
System.out.println("eating...");
}
protected void sleep() {
System.out.println("sleeping...");
}
public Animal(String color, int age){
this.color = color;
this.age = age;
} // ... public getters and setters next
} // continued ...
Why would we use ‘this’?
Include attributes of:
• Colour
• Age
Methods for:
• Eat
• Sleep
Constructor that initialises:
• Colour
• Age
What is missing?
Example: extended Animal class
class Dog extends Animal {
// one attribute only for Dog class
private int collarSize;
// bark() is a method only for Dog class
public void bark(){
System.out.println( "barking...” );
}
@Override // optional annotation
public void sleep(){
//re-defines the sleep() method
System.out.println( "sleep only at night.” );
}
public Dog(String color, int age, int collarSize){
super(color,age); //call superclass’s constructor
this.collarSize = collarSize;
}
} // continued ...
Example: extended Animal class
public class AnimalApp {
public static void main(String args[]){
Dog d = new Dog("black",5,10);
d.bark(); //a method defined in the current class
d.eat(); //a method inherited from its superclass
d.sleep(); //an overriding method
}
}
Output:
barking...
eating...
sleep only at night.
Constructors
Constructors are not inherited.
• Each class defines its own constructors.
• But the constructor of the superclass can be invoked from the
subclass, using super().
Example: constructors
class Animal{
public Animal(String color, int age){
this.color = color;
this.age = age;
} ... // other methods, attributes
}
class Dog extends Animal{
public Dog(String color, int age, int collarSize){
super(color,age); //call superclass’s constructor, must be the first statement
this.collarSize = collarSize;
} ... // other methods, attributes
}
The super keyword
super refers to the superclass.
• Call the superclass’s constructor
• super(color, age);
• Call the superclass’s method
• super.sleep();
• Call the superclass’s hiding attribute
• int age = super.age;
The Object class
• All Java classes are derived from a common root class called Object. If one
class doesn’t extends any class in its definition, it is a subclass of the Object
class.
public class Rectangle {
// its superclass is the Object – how could that be written?
}
Becomes:
public class Rectangle extends Object {
// its superclass is the Object
}
The Object class
• Commonly used methods in Object class:
• toString() //Returns a string representation of the object
• equals(Object obj) //Indicates if two objects equals
• getClass() //Returns the runtime class of this Object
• ...
• All Java classes either inherit or override these methods. See full list:
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html
Inheritance summary
• Keywords: extends, super
• In Java, a class can extends at most one superclass
• A subclass CAN
• inherit attributes and methods (protected or public)
• also default members if in the same package
• add attributes, methods
• override instance methods
• hide attributes (not recommended)
• A subclass CANNOT
• inherit constructors
• inherit private members (attributes and methods)
• override static methods
What does this mean?
Casting
• As a dog is also an animal, we can do as follows.
// Reference is of Animal type
// instance is of Dog type
Animal d = new Dog("black",5,10); // upcasting
• Upcasting: assign a subclass instance to a superclass reference.
• Downcasting: revert a substituted instance back to a subclass
reference (probably not a good design).
Upcasting
Animal d = new Dog("black",5,10); //upcasting
• You can invoke all the methods defined in the Animal class
• d.eat(); //the superclass’s method
• d.sleep(); //the subclass’s version is invoked.
• You CANNOT invoke methods defined in the Dog class for the
reference
• d. d.bark(); //compilation error
Upcasting
• Upcasting is always safe, because a subclass instance possesses all the
properties and functions of its superclass.
Animal d = new Dog("black",5,10); //upcasting
Animal c = new Cat(); // upcasting
• Downcasting is not always safe.
• Dog d2 = (Dog)d; //needs type casting operator
• //otherwise, incompatible type error
• Dog d3 = (Dog)c; //throws a ClassCastException
• To avoid this ClassCastException, the common choice is to check the
object’s class before downcasting by using
• the instanceof operator
instanceof
if (d instanceof Dog) {
Dog d2 = (Dog)d; //downcasting safely
}
instanceof is an operator to verify if an object is an instance of a particular class:
Dog d1 = new Dog("black",5,10);
• System.out.println(d1 instanceof Dog);
• System.out.println(d1 instanceof Animal);
• Animal d2 = new Dog("red",2,10);
• System.out.println(d2 instanceof Dog);
• System.out.println(d2 instanceof Animal);
• System.out.println(d2 instanceof Cat);
// true
// true
//upcasting
// true
// true
// false
Learning resources
The workshop homepage
https://mcollison.github.io/JPMC-java-intro-2021/
The course materials
https://mcollison.github.io/java-programming-foundations/
• Session worksheets – updated each week
Additional resources
• Think Java: How to think like a computer scientist
• Allen B Downey (O’Reilly Press)
• Available under Creative Commons license
• https://greenteapress.com/wp/think-java-2e/
• Oracle central Java Documentation –
https://docs.oracle.com/javase/8/docs/api/
• Other sources:
• W3Schools Java - https://www.w3schools.com/java/
• stack overflow - https://stackoverflow.com/
• Coding bat - https://codingbat.com/java

More Related Content

What's hot

Is2215 lecture2 student(2)
Is2215 lecture2 student(2)Is2215 lecture2 student(2)
Is2215 lecture2 student(2)dannygriff1
 
Java Inheritance | Java Course
Java Inheritance | Java Course Java Inheritance | Java Course
Java Inheritance | Java Course RAKESH P
 
Java Inheritance
Java InheritanceJava Inheritance
Java InheritanceVINOTH R
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - InheritanceOum Saokosal
 
Week10 packages using objects in objects
Week10 packages using objects in objectsWeek10 packages using objects in objects
Week10 packages using objects in objectskjkleindorfer
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with JavaJussi Pohjolainen
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfacesDevaKumari Vijay
 
Introduction to oop and java fundamentals
Introduction to oop and java fundamentalsIntroduction to oop and java fundamentals
Introduction to oop and java fundamentalsAnsgarMary
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: InheritanceTareq Hasan
 
First fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionFirst fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionOregon FIRST Robotics
 
Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in JavaWeek9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Javakjkleindorfer
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programmingshinyduela
 
Types of inheritance in java
Types of inheritance in javaTypes of inheritance in java
Types of inheritance in javachauhankapil
 

What's hot (20)

Is2215 lecture2 student(2)
Is2215 lecture2 student(2)Is2215 lecture2 student(2)
Is2215 lecture2 student(2)
 
Java Inheritance | Java Course
Java Inheritance | Java Course Java Inheritance | Java Course
Java Inheritance | Java Course
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - Inheritance
 
Week10 packages using objects in objects
Week10 packages using objects in objectsWeek10 packages using objects in objects
Week10 packages using objects in objects
 
Java
JavaJava
Java
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Unit 3 Java
Unit 3 JavaUnit 3 Java
Unit 3 Java
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
 
ACM init() Day 6
ACM init() Day 6ACM init() Day 6
ACM init() Day 6
 
Introduction to oop and java fundamentals
Introduction to oop and java fundamentalsIntroduction to oop and java fundamentals
Introduction to oop and java fundamentals
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
Introduction to java and oop
Introduction to java and oopIntroduction to java and oop
Introduction to java and oop
 
First fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionFirst fare 2011 frc-java-introduction
First fare 2011 frc-java-introduction
 
Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in JavaWeek9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Java
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
 
Types of inheritance in java
Types of inheritance in javaTypes of inheritance in java
Types of inheritance in java
 

Similar to OOP Inheritance in Java: Understanding Classes, Subclasses, and Polymorphism

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 overridingNithyaN19
 
Java - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptxJava - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptxVikash Dúbēy
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxShaownRoy1
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingShivam Singhal
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1PRN USM
 
full defination of final opp.pptx
full defination of final opp.pptxfull defination of final opp.pptx
full defination of final opp.pptxrayanbabur
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptxEpsiba1
 

Similar to OOP Inheritance in Java: Understanding Classes, Subclasses, and Polymorphism (20)

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
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Java - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptxJava - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptx
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
29c
29c29c
29c
 
29csharp
29csharp29csharp
29csharp
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
full defination of final opp.pptx
full defination of final opp.pptxfull defination of final opp.pptx
full defination of final opp.pptx
 
Inheritance
InheritanceInheritance
Inheritance
 
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)
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
OOPS Characteristics
OOPS CharacteristicsOOPS Characteristics
OOPS Characteristics
 
Java programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- InheritanceJava programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- Inheritance
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 

More from mcollison

Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliabilitymcollison
 
Pi j4.1 packages
Pi j4.1 packagesPi j4.1 packages
Pi j4.1 packagesmcollison
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphismmcollison
 
Pi j3.4 data-structures
Pi j3.4 data-structuresPi j3.4 data-structures
Pi j3.4 data-structuresmcollison
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objectsmcollison
 
Pi j2.2 classes
Pi j2.2 classesPi j2.2 classes
Pi j2.2 classesmcollison
 
Pi j1.0 workshop-introduction
Pi j1.0 workshop-introductionPi j1.0 workshop-introduction
Pi j1.0 workshop-introductionmcollison
 
Pi j1.4 loops
Pi j1.4 loopsPi j1.4 loops
Pi j1.4 loopsmcollison
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operatorsmcollison
 
Pi j1.2 variable-assignment
Pi j1.2 variable-assignmentPi j1.2 variable-assignment
Pi j1.2 variable-assignmentmcollison
 
Pi j1.1 what-is-java
Pi j1.1 what-is-javaPi j1.1 what-is-java
Pi j1.1 what-is-javamcollison
 

More from mcollison (11)

Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
Pi j4.1 packages
Pi j4.1 packagesPi j4.1 packages
Pi j4.1 packages
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Pi j3.4 data-structures
Pi j3.4 data-structuresPi j3.4 data-structures
Pi j3.4 data-structures
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
Pi j2.2 classes
Pi j2.2 classesPi j2.2 classes
Pi j2.2 classes
 
Pi j1.0 workshop-introduction
Pi j1.0 workshop-introductionPi j1.0 workshop-introduction
Pi j1.0 workshop-introduction
 
Pi j1.4 loops
Pi j1.4 loopsPi j1.4 loops
Pi j1.4 loops
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operators
 
Pi j1.2 variable-assignment
Pi j1.2 variable-assignmentPi j1.2 variable-assignment
Pi j1.2 variable-assignment
 
Pi j1.1 what-is-java
Pi j1.1 what-is-javaPi j1.1 what-is-java
Pi j1.1 what-is-java
 

Recently uploaded

Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 

Recently uploaded (20)

Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 

OOP Inheritance in Java: Understanding Classes, Subclasses, and Polymorphism

  • 1. Programming in Java 5-day workshop OOP Inheritance Matt Collison JP Morgan Chase 2021 PiJ3.1: OOP Inheritance
  • 2. Four principles of OOP: 1.Encapsulation – defining a class 2.Abstraction – modifying the objects 3.Inheritance – extending classes 4.Polymorphism – implementing interfaces
  • 3. How do we achieve inheritance through OOP? • Classes and objects: The first order of abstraction. class new • There are lots of things that the same but with different attribute values. • For example people – we all have a name, a height, we have interests and friends. Think of a social media platform. Everyone has a profile but everyone’s profile is unique. • Class inheritance: The second order of abstraction extends super instanceof • The definitions for things can share common features. • For example the administrator account and a user account both require a username, password and contact details. Each of these account would extend a common ‘parent’ account definition. • Polymorphism: The third order of abstraction implements • The definitions for things can share features but complete them in different ways to achieve different behaviours. For example an e-commerce store must have a database binding, a layout schema for the UI but the specific implementations are unique. These aren’t just different values but different functions.
  • 4. Inheritance public class Identifier extends ParentClassIdentifier{ • All subclasses inherit: • Attributes – access to fields to describe the class • Constructors – access to methods to create the object • Methods – access to functions to describe the objects behaviour Assuming typical access modifiers …except attributes – why?
  • 5. Inheritance • Superclass or base, parent class • Subclass or derived, child, extended class • Single inheritance only – there can only be one superclass for each class. This creates a hierarchy or tree.
  • 6. Shapes public Shape { //What goes in here? } public Triangle extends Shape { //What goes in here? }
  • 7. Method overriding – access modifiers Access modifier within class within package global but subclass global private Yes No No No default Yes Yes No No protected Yes Yes Yes No public Yes Yes Yes Yes
  • 8. What can a subclass do? • A subclass can also add its own attributes and methods. • add same-signature methods - method overriding. • add same-name attributes (but not recommended) - attribute hiding. Q: Can anyone give an example of additional functionality you might implement in subclass?
  • 9. Method overriding • Method overriding: A subclass defines a method which has the same name, number and type of parameters, and return type as a method in the superclass. • NOTE: • Recall Method overloading: If a class has multiple methods having the same name but different in parameters. • When overriding a method, it is recommended to use the @Override annotation, though it is optional.
  • 10. Example – write a class for Animal // A demo for inheritance class public class Animal{ // two common attributes for all animals private String color; private int age; // two common methods for all animals public void eat(){ System.out.println("eating..."); } protected void sleep() { System.out.println("sleeping..."); } public Animal(String color, int age){ this.color = color; this.age = age; } // ... public getters and setters next } // continued ... Why would we use ‘this’? Include attributes of: • Colour • Age Methods for: • Eat • Sleep Constructor that initialises: • Colour • Age What is missing?
  • 11. Example: extended Animal class class Dog extends Animal { // one attribute only for Dog class private int collarSize; // bark() is a method only for Dog class public void bark(){ System.out.println( "barking...” ); } @Override // optional annotation public void sleep(){ //re-defines the sleep() method System.out.println( "sleep only at night.” ); } public Dog(String color, int age, int collarSize){ super(color,age); //call superclass’s constructor this.collarSize = collarSize; } } // continued ...
  • 12. Example: extended Animal class public class AnimalApp { public static void main(String args[]){ Dog d = new Dog("black",5,10); d.bark(); //a method defined in the current class d.eat(); //a method inherited from its superclass d.sleep(); //an overriding method } } Output: barking... eating... sleep only at night.
  • 13. Constructors Constructors are not inherited. • Each class defines its own constructors. • But the constructor of the superclass can be invoked from the subclass, using super().
  • 14. Example: constructors class Animal{ public Animal(String color, int age){ this.color = color; this.age = age; } ... // other methods, attributes } class Dog extends Animal{ public Dog(String color, int age, int collarSize){ super(color,age); //call superclass’s constructor, must be the first statement this.collarSize = collarSize; } ... // other methods, attributes }
  • 15. The super keyword super refers to the superclass. • Call the superclass’s constructor • super(color, age); • Call the superclass’s method • super.sleep(); • Call the superclass’s hiding attribute • int age = super.age;
  • 16. The Object class • All Java classes are derived from a common root class called Object. If one class doesn’t extends any class in its definition, it is a subclass of the Object class. public class Rectangle { // its superclass is the Object – how could that be written? } Becomes: public class Rectangle extends Object { // its superclass is the Object }
  • 17. The Object class • Commonly used methods in Object class: • toString() //Returns a string representation of the object • equals(Object obj) //Indicates if two objects equals • getClass() //Returns the runtime class of this Object • ... • All Java classes either inherit or override these methods. See full list: https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html
  • 18. Inheritance summary • Keywords: extends, super • In Java, a class can extends at most one superclass • A subclass CAN • inherit attributes and methods (protected or public) • also default members if in the same package • add attributes, methods • override instance methods • hide attributes (not recommended) • A subclass CANNOT • inherit constructors • inherit private members (attributes and methods) • override static methods What does this mean?
  • 19. Casting • As a dog is also an animal, we can do as follows. // Reference is of Animal type // instance is of Dog type Animal d = new Dog("black",5,10); // upcasting • Upcasting: assign a subclass instance to a superclass reference. • Downcasting: revert a substituted instance back to a subclass reference (probably not a good design).
  • 20. Upcasting Animal d = new Dog("black",5,10); //upcasting • You can invoke all the methods defined in the Animal class • d.eat(); //the superclass’s method • d.sleep(); //the subclass’s version is invoked. • You CANNOT invoke methods defined in the Dog class for the reference • d. d.bark(); //compilation error
  • 21. Upcasting • Upcasting is always safe, because a subclass instance possesses all the properties and functions of its superclass. Animal d = new Dog("black",5,10); //upcasting Animal c = new Cat(); // upcasting • Downcasting is not always safe. • Dog d2 = (Dog)d; //needs type casting operator • //otherwise, incompatible type error • Dog d3 = (Dog)c; //throws a ClassCastException • To avoid this ClassCastException, the common choice is to check the object’s class before downcasting by using • the instanceof operator
  • 22. instanceof if (d instanceof Dog) { Dog d2 = (Dog)d; //downcasting safely } instanceof is an operator to verify if an object is an instance of a particular class: Dog d1 = new Dog("black",5,10); • System.out.println(d1 instanceof Dog); • System.out.println(d1 instanceof Animal); • Animal d2 = new Dog("red",2,10); • System.out.println(d2 instanceof Dog); • System.out.println(d2 instanceof Animal); • System.out.println(d2 instanceof Cat); // true // true //upcasting // true // true // false
  • 23. Learning resources The workshop homepage https://mcollison.github.io/JPMC-java-intro-2021/ The course materials https://mcollison.github.io/java-programming-foundations/ • Session worksheets – updated each week
  • 24. Additional resources • Think Java: How to think like a computer scientist • Allen B Downey (O’Reilly Press) • Available under Creative Commons license • https://greenteapress.com/wp/think-java-2e/ • Oracle central Java Documentation – https://docs.oracle.com/javase/8/docs/api/ • Other sources: • W3Schools Java - https://www.w3schools.com/java/ • stack overflow - https://stackoverflow.com/ • Coding bat - https://codingbat.com/java