Inheritance
Inheritance in Java enables a class to inherit properties and actions from another class,
called a superclass or parent class. A class derived from a superclass is called a subclass or
child group. Through inheritance, a subclass can access members of its superclass (fields
and methods), enforce reuse rules, and encourage hierarchy.
The idea behind inheritance in Java is that we can create new classes that are built upon
existing classes. When we inherit methods from an existing class, we can reuse methods
and fields of the parent class. However, we can add new methods and fields in your current
class also.
Why inheritance?
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
The Syntax of Java Inheritance
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
Types of Inheritance :
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
NOTE: In Java programming, multiple and hybrid inheritance is supported through
interface only. We will learn about interfaces later.
Single Inheritance
When a class inherits another class, it is known as a single
inheritance. In the example given below, Dog class inherits the
Animal class, so there is the single inheritance.
Multilevel Inheritance
When there is a chain of inheritance, it is known as multilevel
inheritance. As you can see in the example given below, BabyDog
class inherits the Dog class which again inherits the Animal class, so there is a multilevel
inheritance.
Hierarchical Inheritance
When two or more classes inherits a single class, it is known
as hierarchical inheritance. In the example given below, Dog
and Cat classes inherits the Animal class, so there is
hierarchical inheritance.
Multiple Inheritance
Multiple Inheritance A class's capacity to inherit traits from several
classes is referred to as multiple inheritances. This notion may be
quite helpful when a class needs features from many sources.
Hybrid Inheritance in Java
The hybrid inheritance is the composition of two or more
types of inheritance. The main purpose of using hybrid
inheritance is to modularize the code into well-defined
classes. It also provides the code reusability.
Abstraction
Abstraction is a process of hiding the implementation details and showing only functionality
to the user.
Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where we type the text and send the message. We do not know the
internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Abstract Class in Java
An abstract class in Java acts as a partially implemented class that itself cannot be
instantiated. It exists only for subclassing purposes, and provides a template for its
subcategories to follow. Abstract classes can have implementations with abstract methods.
Abstract methods are declared to have no body, leaving their implementation to subclasses.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.
Syntax of Abstract Classes
1. public abstract class Shape {
2. public abstract double area();
3. public void display() {
4. System.out.println("This is a shape.");
5. }
6. }
Abstract Method in Java
A method which is declared as abstract and does not have implementation is known as an
abstract method.
1. abstract class Shape{
2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by end user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11. //In real scenario, method is called by programmer or user
12. public class Main{
13. public static void main(String args[]){
14. //In a real scenario, object is provided through method, e.g., getShape() method
15. Shape s=new Circle();
16. s.draw();
17. }
18. }
Method Overloading in Java
Method overloading in Java is the feature that enables defining several methods in a class
having the same name but with different parameters lists. These algorithms may vary with
regard to the number or type of parameters. When a method is called, Java decides which
version of it to execute depending on the arguments given. If we have to perform only one
operation, having the same name of the methods increases the readability of the program.
1. public class MathOperations {
2. public int add(int a, int b) {
3. return a + b;
4. }
5. public double add(double a, double b, double c) {
6. return a + b + c;
7. }
8. }
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.
Example
1. //Java Program to illustrate the use of Java Method Overriding
2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run(){System.out.println("Vehicle is running");}
6. }
7. //Creating a child class
8. class Bike extends Vehicle{
9. //defining the same method as in the parent class
10. void run(){System.out.println("Bike is running safely");}
11. }
12. //Creating a Main class to create object and call method
13. public class Main{
14. public static void main(String args[]){
15. Bike obj = new Bike();//creating object
16. obj.run();//calling method
17. }
18. }
A Real World Example of Java Method Overriding
Consider a scenario where Bank is a class that provides functionality to get the rate of
interest. However, the rate of interest varies according to banks. For example, SBI, ICICI and
AXIS banks could provide 8%, 7%, and 9% rate of interest.
Polymorphism:
In Java, polymorphism, meaning "many forms," is a core concept of object-oriented
programming that allows objects of different classes to be treated interchangeably based on
shared behavior. It enables flexible and reusable code by allowing one interface to be used
with multiple types of objects.
Types of Polymorphism
1. Compile-time Polymorphism (Method Overloading): Achieved by defining multiple
methods with the same name but different parameters within the same class.
2. Runtime Polymorphism (Method Overriding): Achieved when a subclass provides
a specific implementation of a method already defined in its superclass.
Java Encapsulation
Encapsulation is a fundamental principle of object-oriented programming (OOP) in Java that
involves bundling the data (variables) and the methods (functions) that operate on the data
into a single unit, known as a class. It restricts direct access to some of an object's
components and can prevent the accidental modification of data.
Purpose of Encapsulation
Data Hiding: Encapsulation allows the internal representation of an object to be
hidden from the outside. Only the necessary details are exposed through a public
interface.
Increased Flexibility: By controlling access to the fields of a class, you can change
the internal implementation without affecting the external code using the class.
Improved Maintainability: Encapsulation helps in maintaining the code by keeping
the fields private and providing public getter and setter methods to modify and view
the fields.
Implementing Encapsulation in Java
To achieve encapsulation in Java:
1. Declare the class variables as private.
2. Provide public getter and setter methods to access and update the value of a private
variable.
3. Example 1: Basic Encapsulation
4. public class Student {
5. private String name;
6. private int age;
7.
8. // Getter method for name
9. public String getName() {
10. return name;
11. }
12.
13. // Setter method for name
14. public void setName(String name) {
15. this.name = name;
16. }
17.
18. // Getter method for age
19. public int getAge() {
20. return age;
21. }
22.
23. // Setter method for age
24. public void setAge(int age) {
25. if (age > 0) {
26. this.age = age;
27. }
28. }
29. }
Example 2: Encapsulation with Validation
public class BankAccount {
private double balance;
// Getter method for balance
public double getBalance() {
return balance;
}
// Setter method for balance with validation
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
}
}
}
30.