Introduction to Java Inheritance and Polymorphism. Types of Inheritance as Single, Multiple, Multi-Level, Hybrid, and Hierarchical Inheritance. What is Polymorphism? Compile Time Polymorphism & method overloading. Run Time Polymorphism with example.
Access modifiers - public, protected, private, and default.
2. Inheritance
❖ Inheriting the state and behaviours from a class
❖ It is parent child relationship where child can have all the fields and methods.
❖ Child can have new fields and methods other than the methods inherited from
Parents
3. Class Vehicle{
int noofwheels;
String name, manufacturer;
acceleration(){
//method statements
}
}
Class ElectricCars extends Vehicle{
float batterycapacity;
charging(){
//statements can use fields from
Vehicle & ElectricCar
}
}
Child class
Super class
Inheritance Type - Single
6. Polymorphism
❖ An Object or Entity can do action in different ways
❖ With different situation same object possess different qualities.
❖ E.g., A man can be a father, husband, son, employee etc.
❖ In Java, Polymorphism is achieved by two ways
➢ Compile time Polymorphism
➢ Run time Polymorphism
7. Compile Time Polymorphism
❖ Also known as Static Polymorphism
❖ Achieved by Method Overloading in Java
❖ Here call to method is resolved at run time.
❖ Methods have same name but with any of the following difference makes the
method to overload
➢ Different parameters
➢ Different types of parameters
➢ Change in order of parameters
➢ Different return type
8. public class MethodOverloading {
void sum(int a, int b) {
int c = a+b;
System.out.println("sum of value "+c);
}
void sum(int a, double b) {
double c = a+b;
System.out.println("sum of value "+c);
}
void sum(double a, int b) {
double c = a+b;
System.out.println("sum of value "+c);
}
int sum(int a, int b, int c) {
int d = a+b+c;
System.out.println("sum of value "+c);
return d;
}
}
9. Run time Polymorphism
❖ Overloaded method is called by a reference variable of Parent / Super class
❖ In Real world example, 3 programmers are working on a module Bikes
➢ One in Bikes base class
➢ Other working in BWM class which is extended from Bikes class
➢ Other working in Unicorn class which is extended from Bikes class
❖ Each Class have the method acceleration and each bikes have different acceleration
❖ So one can create object for a child class(unicorn/BMW) with reference from Parent
class(Bikes)
Check this for detailed explanation
10. What is Access Modifiers
❖ Describes the Scope (or) Accessibility of a state or behaviour or class itself
❖ This will create the visibility of the fields, constructor or methods or class to
other entities.
❖ Four Majorly used Access modifiers are
➢ Private
➢ Default
➢ Public
➢ Protected
11. Access Modifier Within Class Within Package Outside Package
Private Y N N
Default Y Y N
Protected Y Y N
Public Y Y Y
extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality