This 5-day Java workshop covers object-oriented programming (OOP) inheritance. The key concepts discussed include the four pillars of OOP - encapsulation, abstraction, inheritance, and polymorphism. Inheritance allows classes to extend existing classes to share common attributes and methods, while also adding new unique functionality. The workshop provides examples of defining parent and child classes, using inheritance, overriding methods, and casting between classes. Resources for further learning about Java and OOP are also listed.
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.
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