s10 InheritPolymorphism
s10 InheritPolymorphism
◆ Describe inheritance
◆ Explain the types of inheritance
◆ Explain super class and subclass
◆ Explain the use of super keyword
◆ Explain method overriding
◆ Describe Polymorphism
◆ Differentiate type of reference and type of objects
◆ Explain static and dynamic binding
◆ Explain virtual method invocation
◆ Explain the use of abstract keyword
methods from its super class except those with private access specifier.
Members having default accessibility in the super class are not inherited
inherited. However, the child class can invoke the constructor of the super
class from its own constructor.
Hierarchical Multiple
Inheritance Inheritance
• A parent class • A child class
has more than derives from
one child classes more than one
at different parent class
levels
can declare new fields. These members will be specific to the subclass.
can write a new instance method with the same signature as the one in the super
class → method overriding.
can create a new static method with the same signature as the one in the super
class → hiding of the super class method.
where,
class1-name: Specifies the name of the child class.
class2-name: Specifies the name of the parent class.
An overriding method cannot have a weaker access specifier than the access
specifier of the super class method.
subclass can invoke the super class constructor and methods using the keyword
super.
Thus, polymorph refers to an object that can have many different forms.
This principle can also be applied to subclasses of a class that can define their
own specific behaviors as well as derive some of the similar functionality of the
super class.
Downcasting Allows casting the parent reference back to the child type.
❖ Casting a parent object to child type is called downcasting because an object is being
casted to a class lower down in the inheritance hierarchy.
❖ However, downcasting requires explicit type casting by specifying the child class name
in brackets.
❖ For example, PartTimeEmployee oPT2=(PartTimeEmployee) objEmp;
◆ In other languages such as C++, the same can be achieved by using the keyword
virtual.
Abstract method
◆ For example,
public abstract void calculate();
◆ Abstract class serves as a framework that provides certain behavior for other
classes.
◆ The subclass provides the requirement-specific behavior of the existing framework.
◆ Abstract classes cannot be instantiated and they must be subclassed to use the
class members.
◆ The subclass provides implementations for the abstract methods in its parent class.
◆ The syntax for declaring an abstract class is as follows: