Module 3.Docx
Module 3.Docx
● 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).
● 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 superclass 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.
Syntax :
Output
In the above program, when an object of MountainBike class is created, a copy of all methods
and fields of the superclass acquires memory in this object. That is why by using the object of
the subclass we can also access the members of a superclass.
Please note that during inheritance only the object of the subclass is created, not the
superclass. For more, refer to Java Object Creation of Inherited Class.
Example 2: In the below example of inheritance, class Employee is a base class, class
Engineer is a derived class that extends the Employee class and class Test is a driver class to
run the program.
Java// Java Program to illustrate Inheritance (concise) import java.io.*; // Base or Super Class
class Employee { int salary = 60000; } // Inherited or Sub Class class Engineer extends
Employee { int benefits = 10000; } // Driver Class class Gfg { public static void main(String
args[]) { Engineer E1 = new Engineer(); System.out.println("Salary : " + E1.salary +
"\nBenefits : " + E1.benefits); } }
Output
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the
properties and behavior of a single-parent class. Sometimes, it is also known as simple
inheritance. In the below figure, ‘A’ is a parent class and ‘B’ is a child class. The class ‘B’
inherits all the properties of the class ‘A’.
Single inheritance
Java// Java program to illustrate the // concept of single inheritance import java.io.*; import
java.lang.*; import java.util.*; // Parent class class One { public void print_geek() {
System.out.println("Geeks"); } } class Two extends One { public void print_for() {
System.out.println("for"); } } // Driver class public class Main { // Main function public static
void main(String[] args) { Two g = new Two(); g.print_geek(); g.print_for(); g.print_geek(); }
}
Output
2. Multilevel Inheritance
In 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 Inheritance
Java` // Importing required libraries import java.io.; import java.lang.; import java.util.*; //
Parent class One class One { // Method to print "Geeks" public void print_geek() {
System.out.println("Geeks"); } } // Child class Two inherits from class One class Two
extends One { // Method to print "for" public void print_for() { System.out.println("for"); } }
// Child class Three inherits from class Two class Three extends Two { // Method to print
"Geeks" public void print_lastgeek() { System.out.println("Geeks"); } } // Driver class public
class Main { public static void main(String[] args) { // Creating an object of class Three
Three g = new Three();
// Calling method from class One g.print_geek(); // Calling method from class Two
g.print_for(); // Calling method from class Three g.print_lastgeek(); }
}`
Output
3. 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// Java program to illustrate the // concept of Hierarchical inheritance class A { public
void print_A() { System.out.println("Class A"); } } class B extends A { public void print_B()
{ System.out.println("Class B"); } } class C extends A { public void print_C() {
System.out.println("Class C"); } } class D extends A { public void print_D() {
System.out.println("Class D"); } } // Driver Class public class Test { public static void
main(String[] args) { B obj_B = new B(); obj_B.print_A(); obj_B.print_B(); C obj_C = new
C(); obj_C.print_A(); obj_C.print_C(); D obj_D = new D(); obj_D.print_A();
obj_D.print_D(); } }
Output
In Multiple inheritances, one class can have more than one superclass and inherit features
from all parent classes. Please note that Java does not support multiple inheritances with
classes. In Java, we can achieve multiple inheritances only through Interfaces. In the image
below, Class C is derived from interfaces A and B.
Multiple Inheritance
Java// Java program to illustrate the // concept of Multiple inheritance import java.io.*;
import java.lang.*; import java.util.*; interface One { public void print_geek(); } interface
Two { public void print_for(); } interface Three extends One, Two { public void print_geek();
} class Child implements Three { @Override public void print_geek() {
System.out.println("Geeks"); } public void print_for() { System.out.println("for"); } } //
Drived class public class Main { public static void main(String[] args) { Child c = new
Child(); c.print_geek(); c.print_for(); c.print_geek(); } }
Output
5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t support
multiple inheritances with classes, hybrid inheritance involving multiple inheritance is also
not possible with classes. In Java, we can achieve hybrid inheritance only through Interfaces
if we want to involve multiple inheritance to implement Hybrid inheritance.
However, it is important to note that Hybrid inheritance does not necessarily require the use
of Multiple Inheritance exclusively. It can be achieved through a combination of Multilevel
Inheritance and Hierarchical Inheritance with classes, Hierarchical and Single Inheritance
with classes. Therefore, it is indeed possible to implement Hybrid inheritance using classes
alone, without relying on multiple inheritance type.
Hybrid Inheritance
Javapublic class SolarSystem { } public class Earth extends SolarSystem { } public class
Mars extends SolarSystem { } public class Moon extends Earth { }
Now, based on the above example, in Object-Oriented terms, the following are true:-
Output
● The inherited fields can be used directly, just like any other fields.
● We can declare new fields in the subclass that are not in the superclass.
● The inherited methods can be used directly as they are.
● We can write a new instance method in the subclass that has the same signature as the
one in the superclass, thus overriding it (as in the example above, toString() method is
overridden).
● We can write a new static method in the subclass that has the same signature as the
one in the superclass, thus hiding it.
● We can declare new methods in the subclass that are not in the superclass.
● We can write a subclass constructor that invokes the constructor of the superclass,
either implicitly or by using the keyword super.
1. 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.
2. 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.
3. Class Hierarchy: Inheritance allows for the creation of a class hierarchy, which can be
used to model real-world objects and their relationships.
4. 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.
1. 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.
2. 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.
Conclusion
Let us check some important points from the article are mentioned below:
● Default superclass: Except Object class, which has no superclass, every class has one
and only one direct superclass (single inheritance). In the absence of any other explicit
superclass, every class is implicitly a subclass of the Object class.
● Superclass can only be one: A superclass can have any number of subclasses. But a
subclass can have only one superclass. This is because Java does not support multiple
inheritances with classes. Although with interfaces, multiple inheritances are
supported by Java.
● Inheriting Constructors: A subclass inherits all the members (fields, methods, and
nested classes) from its superclass. Constructors are not members, so they are not
inherited by subclasses, but the constructor of the superclass can be invoked from the
subclass.
● Private member inheritance: A subclass does not inherit the private members of its
parent class. However, if the superclass has public or protected methods(like getters
and setters) for accessing its private fields, these can also be used by the subclass.
FAQs in Inheritance
1. What is Inheritance Java?
Inheritance is a concept of OOPs where one class inherits from another class that can reuse
the methods and fields of the parent class.
Consider a group of vehicles. You need to create classes for Bus, Car, and Truck. The
methods fuelAmount(), capacity(), applyBrakes() will be the same for all three classes.
Polymorphism
The word ‘ polymorphism’ means ‘ having many forms’. In Java, polymorphism refers to
the ability of a message to be displayed in more than one form. This concept is a key feature
of Object-Oriented Programming and it allows objects to behave differently based on their
specific class type.
Real-life Illustration of Polymorphism in Java: A person can have different characteristics
at the same time. Like a man at the same time is a father, a husband, and an employee. So the
same person possesses different behaviors in different situations. This is called
polymorphism.
Example: A Person Having Different Roles
Java` // Base class Person class Person {
// Method that displays the // role of a person void role() { System.out.println("I am a
person."); }
} // Derived class Father that // overrides the role method class Father extends Person {
// Overridden method to show // the role of a father @Override void role() {
System.out.println("I am a father."); }
} public class Main { public static void main(String[] args) {
// Creating a reference of type Person // but initializing it with Father class object Person p =
new Father(); // Calling the role method. It calls the // overridden version in Father class
p.role(); }
}`
Output
I am a father.
Explanation: In the above example, the Person class has a method role() that prints a
general message. The Father class overrides role() to print a specific message. The
reference of type Person is used to point to an object of type Father, demonstrating
polymorphism at runtime. The overridden method in Father is invoked when role() is called.
● Compile-Time Polymorphism
● Runtime Polymorphism
1. Compile-Time Polymorphism
Compile-Time Polymorphism in Java is also known as static polymorphism. This type of
polymorphism is achieved by function overloading or operator overloading.
Note: But Java doesn’t support the Operator Overloading.
Method Overloading
Method overloading in Java means when there are multiple functions with the same name but
different parameters then these functions are said to be overloaded. Functions can be
overloaded by changes in the number of arguments or/and a change in the type of arguments.
Example: Method overloading by changing the number of arguments
Java` // Method overloading By using // Different Types of Arguments // Class 1 // Helper
class class Helper { // Method with 2 integer parameters static int Multiply(int a, int b) { //
Returns product of integer numbers return a * b; } // Method 2 // With same name but with 2
double parameters static double Multiply(double a, double b) { // Returns product of double
numbers return a * b; } } // Class 2 // Main class class Geeks { // Main driver method public
static void main(String[] args) {
// Calling method by passing // input as in arguments System.out.println(Helper.Multiply(2,
4)); System.out.println(Helper.Multiply(5.5, 6.3)); }
}`
Output
8 34.65
Subtypes of Compile-time Polymorphism:
● Function Overloading: It is a feature in C++/Java where multiple functions can have the same
name but with different parameter lists. The compiler will decide which function to call
based on the number and types of arguments passed to the function.
● Operator Overloading: It is a feature in C++ where the operators such as +, -, *, etc. can be
given additional meanings when applied to user-defined data types.
● Template: It is a powerful feature in C++ that allows us to write generic functions and classes.
A template is a blueprint for creating a family of functions or classes.
2. Runtime Polymorphism
Runtime Polymorphism in Java known as Dynamic Method Dispatch. It is a process in which
a function call to the overridden method is resolved at Runtime. This type of polymorphism is
achieved by Method Overriding. Method overriding, on the other hand, occurs when a
derived class has a definition for one of the member functions of the base class. That base
function is said to be overridden.
Method Overriding
Java// Java Program for Method Overriding // Class 1 // Helper class class Parent { // Method
of parent class void Print() { System.out.println("parent class"); } } // Class 2 // Helper class
class subclass1 extends Parent { // Method void Print() { System.out.println("subclass1"); } }
// Class 3 // Helper class class subclass2 extends Parent { // Method void Print() {
System.out.println("subclass2"); } } // Class 4 // Main class class Geeks { // Main driver
method public static void main(String[] args) { // Creating object of class 1 Parent a; // Now
we will be calling print methods // inside main() method a = new subclass1(); a.Print(); a =
new subclass2(); a.Print(); } }
Output
subclass1 subclass2
Explanation: In the above example, when an object of a child class is created, then the
method inside the child class is called. This is because the method in the parent class is
overridden by the child class. Since the method is overridden, This method has more priority
than the parent method inside the child class. So, the body inside the child class is executed.
Subtype of Run-Time Polymorphism
Virtual Functions: It allows an object of a derived class to behave as if it were an object of
the base class. The derived class can override the virtual function of the base class to provide
its own implementation. The function call is resolved at runtime, depending on the actual
type of the object.
Advantages of Polymorphism
● Can make it more difficult to understand the behavior of an object, especially if the code is
complex.
● This may lead to performance issues, as polymorphic behavior may require additional
computations at runtime.
Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.
Private and final methods can be Private and final methods can’t be
overloaded. overridden.
Example:
Java` {...} //Driver Code Starts{ import java.io.*; // Interface Declared //Driver Code Ends }
interface testInterface {
// public, static and final final int a = 10; // public and abstract void display();
} // Class implementing interface class TestClass implements testInterface {
// Implementing the capabilities of // Interface public void display(){
System.out.println("Geek"); }
} class Geeks {...} //Driver Code Starts{ { public static void main(String[] args) { TestClass t
= new TestClass(); t.display(); System.out.println(t.a); } } //Driver Code Ends } `
Output
Geek 10
Note: In Java, the abstract keyword applies only to classes and methods, indicating that they
cannot be instantiated directly and must be implemented. When we decide on a type of entity
by its behaviour and not via attribute we should define it as an interface.
Syntax
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
To declare an interface, use the interface keyword. It is used to provide total abstraction. That
means all the methods in an interface are declared with an empty body and are public and all
fields are public, static, and final by default. A class that implements an interface must
implement all the methods declared in the interface. To implement the interface, use the
implements keyword.
Example:
Java` import java.io.*; // Add interface interface Add{ int add(int a,int b); } // Sub interface
interface Sub{ int sub(int a,int b); } // Calculator class implementing // Add and Sub class Cal
implements Add , Sub { // Method to add two numbers public int add(int a,int b){ return a+b;
}
// Method to sub two numbers public int sub(int a,int b){ return a-b; }
} class GFG{ // Main Method public static void main (String[] args) { // instance of Cal class
Cal x = new Cal();
System.out.println("Addition : " + x.add(2,1)); System.out.println("Substraction : " +
x.sub(2,1)); }
}`
Output
Addition : 3 Substraction : 1
Java` // interfaces can have methods from JDK 1.8 onwards interface TestInterface { final int
a = 10;
default void display() { System.out.println("hello"); }
} // A class that implements the interface. class TestClass implements TestInterface { //
Driver Code public static void main (String[] args) { TestClass t = new TestClass();
t.display(); } } `
Output
hello
2. Static Methods
Another feature that was added in JDK 8 is that we can now define static methods in
interfaces that can be called independently without an object. These methods are not
inherited.
Javainterface TestInterface { final int a = 10; static void display() {
System.out.println("hello"); } } // A class that implements the interface. class TestClass
implements TestInterface { // Driver Code public static void main (String[] args) {
TestInterface.display(); } }
Output
hello
Extending Interfaces
One interface can inherit another by the use of keyword extends. When a class implements an
interface that inherits another interface, it must provide an implementation for all methods
required by the interface inheritance chain.
Java` interface A { void method1(); void method2(); } // B now includes method1 // and
method2 interface B extends A { void method3(); } // the class must implement // all method
of A and B. class GFG implements B { public void method1() { System.out.println("Method
1"); }
public void method2() { System.out.println("Method 2"); } public void method3() {
System.out.println("Method 3"); } public static void main(String[] args){ // Instance of GFG
class created GFG x = new GFG(); // All Methods Called x.method1(); x.method2();
x.method3(); }
}`
Output
Method 1 Method 2 Method 3
In a Simple way, the interface contains multiple abstract methods, so write the
implementation in implementation classes. If the implementation is unable to provide an
implementation of all abstract methods, then declare the implementation class with an
abstract modifier, and complete the remaining method implementation in the next created
child classes. It is possible to declare multiple child classes but at final we have completed
the implementation of all abstract methods.
In general, the development process is step by step:
Level 1 – interfaces: It contains the service details.
Level 2 – abstract classes: It contains partial implementation.
Level 3 – implementation classes: It contains all implementations.
Level 4 – Final Code / Main Method: It have access of all interfaces data.
Example:
Java// implementation Level wise import java.io.*; import java.lang.*; import java.util.*; //
Level 1 interface Bank { void deposit(); void withdraw(); void loan(); void account(); } //
Level 2 abstract class Dev1 implements Bank { public void deposit() {
System.out.println("Your deposit Amount :" + 100); } } abstract class Dev2 extends Dev1 {
public void withdraw() { System.out.println("Your withdraw Amount :" + 50); } } // Level 3
class Dev3 extends Dev2 { public void loan() {} public void account() {} } // Level 4 class
Main { public static void main(String[] args) { Dev3 d = new Dev3(); d.account(); d.loan();
d.deposit(); d.withdraw(); } }Try it on GfG Practice \ \
Output
Your deposit Amount :100 Your withdraw Amount :50
Advantages of Interfaces
● Without bothering about the implementation part, we can achieve the security of the
implementation.
● In Java, multiple inheritances are not allowed, however, you can use an interface to make use
of it as you can implement more than one interface.
Important Points
In the article, we learn certain important points about interfaces as mentioned below:
● We can’t create an instance (interface can’t be instantiated) of the interface but we can make
the reference of it that refers to the Object of its implementing class.
● A class can implement more than one interface.
● An interface can extend to another interface or interface (more than one interface).
● A class that implements the interface must implement all the methods in the interface.
● All the methods are public and abstract. All the fields are public, static, and final.
● It is used to achieve multiple inheritances.
● It is used to achieve loose coupling.
● Inside the Interface not possible to declare instance variables because by default variables
are public static final.
● Inside the Interface, constructors are not allowed.
● Inside the interface main method is not allowed.
● Inside the interface, static, final, and private methods declaration are not possible.
FAQs
1. What is a marker or tagged interface?
Tagged Interfaces are interfaces without any methods they serve as a marker without any
capabilities.