CS102 Chapter4 INHERITANCE POLYMORPHISM
CS102 Chapter4 INHERITANCE POLYMORPHISM
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
Subclasses can extend the functionality of the superclass by adding new methods or
overriding existing ones.
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.
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){
➢ Each constructor begins by calling the constructor of the super -class: super()
➢ the default constructor (added by the compiler) call the default constructor of the super-class
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.
@Override
public String toString() {
return super.toString() + " my registration number is : " + this. RegisID;
}
@Override
public String toString() {
return super.toString() + " my salary is: " + this.Salairy + " D";
}
@Override
public String toString() {
return super.toString() + " my speciality is : " +this.speciality;
}
➢ It is rarely useful, but generally a bad idea since it presents a source of error
Solution : casting using (cast) allow to change or convert the type of the declared reference (or object)
class A {
int x = 1;
}
class B extends A {
String x = " z z " ;
}
class C extends B {
boolean x = t r u e ;
➢ 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
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 ) ;
}
}
➢ 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
}
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();
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();
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.
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.
Output:
Dog barks
Dog fetches the ball
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.