0% found this document useful (0 votes)
71 views32 pages

CS102 Chapter4 INHERITANCE POLYMORPHISM

This document discusses object-oriented programming concepts like inheritance, polymorphism, and inheritance in Java. It defines key terms, provides examples of inheritance in code, and describes how to create subclasses that extend parent classes and override methods.

Uploaded by

azzaguidara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views32 pages

CS102 Chapter4 INHERITANCE POLYMORPHISM

This document discusses object-oriented programming concepts like inheritance, polymorphism, and inheritance in Java. It defines key terms, provides examples of inheritance in code, and describes how to create subclasses that extend parent classes and override methods.

Uploaded by

azzaguidara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

CS102 OBJECT ORIENTED PROGRAMMING

CHAPTER 4
INHERITANCE AND POLYMORPHISM

4/12/2024 1
Outline

• Introduction
• Java Inheritance
• Objects instantiating derived classes
• Constructors
• Hidden fields
• Instanceof operator
• Method overriding
• Method overloading
• Typecasting
• Java Polymorphism

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 2


Introduction
The used / developed classes may have common characteristics, common behaviors
or also common signatures of methods.
In Java, inheritance refers to the mechanism by which a class can inherit properties and
behaviors (methods) from another class.

• The class being inherited from is called


the superclass or base class.
• The class inheriting from it is called
the subclass or derived class.

Subclasses can extend the functionality of the superclass by adding new methods or
overriding existing ones.

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 3


Java Inheritance
Important Terms in Java Inheritance
1. Class: Class is a user-defined datatype in Java that is basically a group of objects. It is a blueprint or
template from which we create objects.

2. Super Class: The class whose features and functionalities are being inherited or used is known as the
superclass or a base class or a parent class.

3. Sub Class: The class that inherits the properties and features from another class is known as a subclass or a
derived class or extended class or child class. The subclass can add its own features and functions in addition
to the fields and methods of its superclass or the parent class.

4. The extends keyword: The keyword extends is used by child class while inheriting the parent class.

5. The super keyword: The super keyword is similar to this keyword. The following are some cases where we use
super keyword :
✓ There are some situations where the members of the superclass and the subclass have the same names,
then the super keyword is used to differentiate the members of the superclass from the members of the
subclass.
✓ To invoke the superclass constructor from the subclass.

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 4


Java Inheritance
Example

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 5


Objects instantiating derived classes
Each object instantiating a derived class is considered primarily as an object instantiating the base class

➢ First, a Box is a Rectangle

Each object instantiating a derived class combines the derived attributes from the base class with those
defined in its own class

➢We have double length and double width in objects of the Rectangle class, and we also have double
height for each object of Box class
public class test{
public static void main (String [] args){

Rectangle rec = new Rectangle();


rec.setRectangle(2.5, 4.5);
System.out.println(rec.getArea());

Box b = new Box();


b.setBox(2,3.5,2.5);
System.out.println(b.getVolume());
}
}
4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 6
Constructors
The construction (and initialization) of all classes instances begins at first by constructing
(initializing) an object instance

➢ Each constructor begins by calling the constructor of the super -class: super()

➢ It should be the first instruction of the constructor

➢ the default constructor (added by the compiler) call the default constructor of the super-class

public class Box extends Rectangle {


public class R e c t a n g l e {
private d o u b l e h e i g h t ;
private double length;
private double width; public Box() {
public Rectangle(double l, double w) { // super(); // Constructor Rectangle() is undefined
this.length = l; super(0,0); // OK
this.width = w; } }
// … }
}

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 7


Example
Description
- The class Student inherits from the class Person.
- The class Professor inherits from the class Employee (salary : double) which inherits from the class Person
-A Student (RegistrationID : String) is a Person having the following characateristics(ID, FirstName, LastName : String).
-A Professor (speciality: String) is an Employee and an Employee is a Person.

Questions
-Write all the needed classes in Java.
-Each class should contain a constructor for initializing the objects to be created.
-Each class should redefine the method toString().
-Write a principal program in separate class to create two students, two professors and two employees.
The program should display all the information about the created objects.

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 8


Example – classes definition
Class Person
public class Person {
protected int id;
protected String FName, LName ;
private static int count;

public Person (String LN, String FN) {


this.id = ++count;
this.FName = FN;
this.LName = LN;
System.out.println(" a new person is created ");
}
@Override
public String toString() {
return ”I am " + this.LName.toUpperCase() + " "
+ this.FName.substring(0, 1).toUpperCase() + ""
+ this.FName.substring(1).toLowerCase();
}
}

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 9


Example – classes definition
Class Student
public class Student extends Person {

private String RegisID;

public Student(String LN, String FN, String id) {


super(LN, FN);
this.RegisID = id;
System.out.println(" a new student is created ");
}

@Override
public String toString() {
return super.toString() + " my registration number is : " + this. RegisID;
}

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 10


Example – classes definition
Class Employee
public class Employee extends Person {

protected double Salary;

public Employee(String LN, String FN, double S) {


super(LN, FN);
this.salary = s;
System.out.println(“a new employee is created”);
}

@Override
public String toString() {
return super.toString() + " my salary is: " + this.Salairy + " D";
}

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 11


Example – classes definition
Class Professor
public class Professor extends Employee {

private String Speciality;

public Professor(String LN, String FN, double S, String Sp) {


super(LN, FN, S);
this.Speciality = sp;
System.out.println(" a new professor is created ");
}

@Override
public String toString() {
return super.toString() + " my speciality is : " +this.speciality;
}

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 12


Example – principal program
Principal program

public class Program {


public static void main(String[ ] main) {
Employee[ ] E = new Employee[2];
E[0] = new Employee("Gharbi", "Rachid", 10000);
E[1] = new Employee("Slama", "Ahmed", 10000);
System.out.println(E[0]);
System.out.println(E[1]);

Student[] S = new Student[2];


S[0] = new Student(”Salhi", ”Ahmed", "65678754");
S[1] = new Student(”Abidi", ”Leila", "87543543");
System.out.println(S[0]);
System.out.println(S[1]);

Professor[] P = new Professor[2];


P[0] = new Professor("Fersi", "Maya", 5700, "JAVA/JEE");
P[1] = new Professor("Gharbi", "Ali", 5000, "Maths");
System.out.println(P[0]);
System.out.println(P[1]);
}
}

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 13


Exercise
In this example, we will create Circle and Cylinder classes: Cylinder is a subclass of Circle.

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 14


Hidden fields - comments
It is not possible to create an attribute in a child-class having the same name as another belonging to
the mother-class

➢ It is rarely useful, but generally a bad idea since it presents a source of error

Super ➔ this seen with the type of the super-class

➢ super.super.x does not exist neither ref.super.x

We can only use ref.super

Solution : casting using (cast) allow to change or convert the type of the declared reference (or object)

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 15


Hidden fields - comments

class A {
int x = 1;
}

class B extends A {
String x = " z z " ;
}

class C extends B {
boolean x = t r u e ;

public s t a t i c void m a i n ( S t r i n g [ ] args){


C obj = new C ( ) ;
System.out.println(obj.x); / / true
S y s t e m . o u t . p r i n t l n ( ( ( B ) o b j ) . x ) ; / / zz
System.out.println(((A)obj).x); / / 1
}
}

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 16


Instanceof operator
It is possible to perform the conversion/casting correctly without exceptions thanks to the operator instanceof ➔
x instanceof T

➢ X should be a variable which references an object or null

➢ T is a type (primitive, non-primitive, class, etc)

➢ The result is true when x is not null and can be assigned to a variable of type T, otherwise, it is false.

A ab = n u l l ;
class A { }
System .out .pr intln( ab instanceof A); // false
Class B extends A{ }
ab = new B();
class C extends B{ } System .out .pr intln( ab instanceof A); // true
System .out .pr intln( ab instanceof B); // true
System .out .pr intln( ab instanceof C); // false

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 17


Method overriding
Giving antoher implementation to the same method:

➢ Same name, same parameters, different code

public class P i x e l {
private i n t x ;
private i n t y ;
public class ColoredPixel extends P i x e l {
public Pixel(int newX, int newY) { private b y t e [ ] r g b ;
this.x = newX;
public void display() {
this.y = newY;
super.display();
} System.out.println("["+rgb[0]+":"+rgb[1]+":"+rgb[2]+"]");
public void display() {
}
System.out.println(x);
}
System.out. pr i n t l n( y ) ;
}
}

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 18


Method overloading
If the method signature is different from the one defined in the super class, it is called overloading

➢ Both methods have the same name but have different parameters
Generally, both are defined in the same child class

class P i x e l {
void m1() { . . . }
void m2() { . . . }
Pixel m3() { . . . }
void m4(Pixel p ) { . . . }
}
class C o l o r e d P i x e l extends P i x e l {
void m1() { . . . } / / o v e r r i d i n g
void m2(int a ) { . . . } / / overloading
ColoredPixel m3() { . . . } / / o v e r r i d i n g
void m4(Pixel p ) { . . . } / / overriding
void m4(ColoredPixel p ) { . . . } / / overloading
}

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 19


Example – classes definition

public class Employee{


protected String name ;
protected double salary ;
public Employee ( String n , double s ) {
this.name = n ;
t hi s . sala ry = s ; }
public String getName() { return name ; }
public double getSalary() { return salary ; }
public String t oSt r ing() { return name +" "+ salary ; }
}

public class Chief extends Employee{


protected double bonus ;
public Chief ( String n , double s , double b ) {
super( n, s ) ;
this.bonus = b ; }
public double getSalary() {
return salary + bonus; } / / r e t u r n s u p e r. g e t S a l a i r e ( ) + bonus;
}

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 20


Example – principal program
Employee e[] = new Employee[5] ;
e[0] = new Chief("Cronos", 1000, 500) ;
e[1] = new Chief("Zeus " , 1000, 600) ;
e[2] = new Employee("Ares", 620) ;
e[3]= new Employee ("Apollon", 700) ;
e[4]= new Employee ("Aphrodite " , 100) ;

for ( i n t i = 0 ; i < 5 ; i + + ) {
i f ( e [ i ] instanceof Chief)
System.out.print("Chief : “ ) ; //add “Chief” if the employee is a chief

System.out.println(e [ i ] . t o S t r i n g ( ) ) ; }

double sumSalaries = 0;
for ( i n t i = 0 ; i < 5 ; i++)
i f ( ! ( e [ i ] instanceof Chief)) //add the salary if the employee is not a chief

sumSalaries += e[i].getSalary();

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 21


Typecasting
Upcasting is the typecasting from a subclass to a superclass (Child to Parent class).
In this way, we can access the properties (methods and variables) of the superclass, i.e., the
Parent as well.
Downcasting is typecasting from a superclass to a subclass so that we can access the
methods of the subclass, i.e., the child class.

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 22


Typecasting
Upcasting in Java
Upcasting, in simpler words, is the typecasting of a child object to a parent object.

Notice in this image that the reference variable is of the type Parent whereas the object is
created of the type Child. This is known as upcasting. The reason is that the child object created
here can show the properties of its parent, therefore it's correct to put the reference of its
parent.

Syntax of Upcasting
Parent obj = new Child();

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 23


Typecasting
Upcasting in Java
/* Java program to demonstrate upcasting */ //Creating a child class Football
import java.io.*; class Football extends Sport{
import java.util.*; //Method to display name
void displayName(){
//Creating a parent class Sport System.out.println("Football");
class Sport{ }
//Method to display name }
void displayName(){
System.out.println("Sport"); public class Main {
} public static void main (String[] args) {
} //Upcasting
Sport sport1 = new Cricket();
//Creating a child class Cricket //calling method
class Cricket extends Sport{ sport1.displayName();
//Method to display name
void displayName(){ //Upcasting
System.out.println("Cricket"); Sport sport2 = new Football();
} //calling method
} sport2.displayName();
}
}

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 24


Typecasting
Downcasting in Java
Downcasting refers to typecasting a parent object to a child object.
However, this cannot be an implicit typecasting.
Why?
Because it's correct to say that Cricket is a Sport or Football is a Sport. But, we cannot say
that, in particular, Sport is a Cricket or Sport is Football.

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 25


Typecasting
Downcasting in Java
* While downcasting, it is important to verify beforehand that the object created is of the
type Child irrespective of the reference variable. This tells the compiler the runtime type of
the object.
Sport sport= new Cricket();
Cricket castedToCricket= (Cricket) sport;

We created an object of the type Cricket with the reference to the type Sport. The explicit
casting informs the compiler about the runtime type of the object. Since the object creation
type was Cricket initially, downcasting is possible in this case.

** Let's take up another scenario where downcasting isn't possible.


Sport sport= new Sport();
Cricket notCastedToCricket= (Cricket) sport;

This superclass-to-subclass casting is not possible because the runtime object of the sport is
Sport. It should be Cricket, like in the above case.

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 26


Typecasting - Example
class Animal { public class Main {
void makeSound() { public static void main(String[] args) {
System.out.println("Animal makes a sound");
} Animal myAnimal = new Dog();
}
myAnimal.makeSound(); //call the makeSound method of Dog
class Dog extends Animal {
void makeSound() { // Downcasting to access subclass-specific method
System.out.println("Dog barks"); if (myAnimal instanceof Dog) {
}
Dog myDog = (Dog) myAnimal;
void fetch() { myDog.fetch(); // This calls the fetch method of Dog
System.out.println("Dog fetches the ball"); }
} }
} }

Output:
Dog barks
Dog fetches the ball

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 27


Typecasting - Example
public class Main {
class Animal { public static void main(String[] args) {
void makeSound() {
System.out.println("Animal makes a sound"); Animal a[] = new Animal[3];
} a[0] = new Animal();
} a[1] = new Dog();
a[2] = new Dog();
class Dog extends Animal {
void makeSound() { for (int i=0;i<3;i++){
System.out.println("Dog barks"); a[i].makeSound(); //call the makeSound method of Dog
} }
for (int i=0;i<3;i++){
void fetch() { // Downcasting to access subclass-specific method
System.out.println("Dog fetches the ball"); if (a[i] instanceof Dog) {
}
}
Output: Dog myDog = (Dog) a[i];
Animal makes a sound myDog.fetch(); // This calls the fetch method of Dog
Dog barks }
Dog barks }
}
Dog fetches the ball
}
Dog fetches the ball

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 28


Typecasting
Difference between Upcasting and Downcasting in Java

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 29


Java Polymorphism

Polymorphism means "many forms", and it occurs when we have many classes
that are related to each other by inheritance.
Inheritance allows to inherit attributes and methods from another
class. Polymorphism uses those methods to perform different tasks. This allows us to
perform a single action in different ways based on the context.

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 30


Java Polymorphism
Example
Suppose that there is a superclass called Animal that has a method called animalSound().
Subclasses of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own
implementation of an animal sound (the pig oinks, and the cat meows, etc.)
class Animal {
class Main {
public void animalSound() {
public static void main(String[] args) {
System.out.println("The animal makes a sound");
Animal myAnimal = new Animal(); //Create an Animal object
}
Animal myPig = new Pig(); // Create a Pig object
}
Animal myDog = new Dog(); // Create a Dog object
class Pig extends Animal {
myAnimal.animalSound(); // The animal makes a sound
public void animalSound() {
myPig.animalSound(); // The pig oinks
System.out.println("The pig oinks");
myDog.animalSound(); // The dog barks
}
}
}
}
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog barks");
}
}

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 31


Exercise
Write a Java program to create a class Employee with
a method called calculateSalary().

Create two subclasses Manager and Programmer.


In each subclass, override the calculateSalary()
method to calculate and return the salary based on
their specific roles.

In the main program, create an array of


2 Employees: a manager and a programmer.
Display “manager” or “programmer” for every
employee followed by toString() output.

4/12/2024 SOUTH MEDITERRANEAN UNIVERSITY 32

You might also like