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/ 33
Unit 4
Inheritance & Polymorphism
Introduction • Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system). • The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. • Inheritance represents the IS-A relationship which is also known as a parent- child relationship. Need of Inheritance • Code Reusability: The code written in the Superclass is common to all subclasses. Child classes can directly use the parent class code.
• Method Overriding: Method Overriding is achievable
only through Inheritance. It is one of the ways by which Java achieves Run Time Polymorphism.
• Abstraction: The concept of abstract where we do not
have to provide all details is achieved through inheritance. Abstraction only shows the functionality to the user. Important Terminologies Used in Java Inheritance • Class: Class is a set of objects which shares common characteristics/ behavior and common properties/ attributes. Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are created. • Super Class/Parent Class: The class whose features are inherited is known as a superclass(or a base class or a parent class). Important Terminologies Used in Java Inheritance • Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the super class fields and methods. • Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class. Java Inheritance Types 1. Single Inheritance 2. Multilevel Inheritance 3. Hierarchical Inheritance Single Inheritance • In single inheritance, subclasses inherit the features of one superclass. In the image below, class A serves as a base class for the derived class B. Single Inheritance // Java program to illustrate the } // concept of single inheritance import java.io.*; // Driver class import java.lang.*; public class Main { import java.util.*; // Main function public static void main(String[] // Parent class args) class one { { public void print_geek() two g = new two(); { g.print_geek(); System.out.println(“hello"); g.print_for(); } g.print_geek(); } } } class two extends one { Output:- public void print_for() { Hello welcome hello System.out.println(“welcome"); } Multilevel Inheritance • Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class also acts as the base class for other classes. In the below image, class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. In Java, a class cannot directly access the grandparent’s members. Multilevel // Java program to illustrate the Inheritance { // concept of Multilevel inheritance System.out.println(“RMDSTIC"); import java.io.*; } import java.lang.*; } import java.util.*; // Drived class class one { public class Main { public void print_w() public static void main(String[] args) { { System.out.println(“welcome"); three g = new three(); } g.print_w(); } g.print_to(); g.print(); class two extends one { } public void print_to() { } System.out.println(“to"); } } Output:--welcome to RMDSTIC
class three extends two {
public void print() Hierarchical Inheritance • In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the below image, class A serves as a base class for the derived classes B, C, and D. // Java program to illustrate the public class Test { // concept of Hierarchical inheritance public static void main(String[] args) { class A { B obj_B = new B(); public void print_A() { obj_B.print_A(); System.out.println("Class A"); } obj_B.print_B(); } C obj_C = new C(); class B extends A { obj_C.print_A(); public void print_B() { obj_C.print_C(); System.out.println("Class B"); } } D obj_D = new D(); obj_D.print_A(); class C extends A { obj_D.print_D(); public void print_C() { } System.out.println("Class C"); } } }
class D extends A { Class A
public void print_D() { Class B System.out.println("Class D"); } Class A } Class C Class A // Driver Class Class D Benefits of Inheritance • Code Reusability: Inheritance allows for code reuse and reduces the amount of code that needs to be written. The subclass can reuse the properties and methods of the superclass, reducing duplication of code.
• Abstraction: Inheritance allows for the creation of abstract
classes that define a common interface for a group of related classes. This promotes abstraction and encapsulation, making the code easier to maintain and extend.
• Class Hierarchy: Inheritance allows for the creation of a class
hierarchy, which can be used to model real-world objects and their relationships.
• Polymorphism: Inheritance allows for polymorphism, which
is the ability of an object to take on multiple forms. Subclasses can override the methods of the superclass, which allows them to change their behavior in different ways Cost of Inheritance • Complexity: Inheritance can make the code more complex and harder to understand. This is especially true if the inheritance hierarchy is deep or if multiple inheritances is used. • Tight Coupling: Inheritance creates a tight coupling between the superclass and subclass, making it difficult to make changes to the superclass without affecting the subclass. • Inheritance decreases the execution speed due to the increased time and effort it takes, the program to jump through all the levels of overloaded classes. • Inheritance makes the two classes (base and inherited class) get tightly coupled. This means one cannot be used independently of each other. • The changes made in the parent class will affect the behavior of child class too. • The overuse of inheritance makes the program more complex Constructor in derived classes • While implementing inheritance in a Java program, every class has its own constructor. Therefore the execution of the constructors starts after the object initialization. It follows a certain sequence according to the class hierarchy. There can be different orders of execution depending on the type of inheritance. order of constructor execution in Java Single inheritance } /* Parent Class */ class ParentClass public class OrderofExecution1 { { /* Constructor */ /* Driver Code */ ParentClass() public static void main(String ar[]) { { System.out.println("ParentClass constructor /* Create instance of ChildClass */ executed."); System.out.println("Order of constructor } execution..."); } ChildClass c1=new ChildClass(); } /* Child Class */ } class ChildClass extends ParentClass { Output /* Constructor */ Order of constructor execution... ChildClass() ParentClass constructor executed. { ChildClass constructor executed. System.out.println("ChildClass constructor executed."); } order of constructor execution in Java • In the above code, after creating an instance of ChildClass the ParentClass constructor is invoked first and then the ChildClass. order of constructor execution in Java Multilevel inheritance { class College System.out.println("Student constructor executed"); { } /* Constructor */ } College() public class OrderofExecution { { System.out.println("College constructor executed"); /* Driver Code */ } public static void main(String ar[]) } { /* Create instance of Student class */ class Department extends College System.out.println("Order of constructor execution { in Multilevel inheritance..."); /* Constructor */ new Student(); Department() } { } System.out.println("Department constructor Output:- executed"); Order of constructor execution in Multilevel nheritance... } College constructor executed } Department constructor executed Student constructor executed class Student extends Department { /* Constructor */ Student() • In multilevel inheritance, all the upper class constructors are executed when an instance of bottom most child class is created. • In the above code, an instance of Student class is created and it invokes the constructors of College, Department and Student accordingly. Calling superclass constructor using super keyword /* Parent Class */ { class ParentClass System.out.println("Value of a : "+a+"\nValue of b : { "+b); int a; } ParentClass(int x) } { a = x; public class OrderofExecution4 } { } /* Driver Code */ public static void main(String ar[]) /* Child Class */ { class ChildClass extends ParentClass System.out.println("Order of constructor { execution..."); int b; ChildClass d = new ChildClass(79, 89); ChildClass(int x, int y) d.Show(); { } /* Accessing ParentClass Constructor */ } super(x); b = y; Order of constructor execution... } Value of a : 79 /* Method to show value of a and b */ Value of b : 89 void Show() • A child class constructor or method can access the base class constructor or method using the super keyword. • In the above code, the ChildClass calls the ParentClass constructor using a super keyword that determines the order of execution of constructors.