Skip to content

Commit def657d

Browse files
authoredFeb 3, 2025
Update README.md
1 parent 3b0b322 commit def657d

File tree

1 file changed

+86
-324
lines changed

1 file changed

+86
-324
lines changed
 

‎Day_16_Inheritance/README.md

+86-324
Original file line numberDiff line numberDiff line change
@@ -1,401 +1,163 @@
1-
# Java Inheritance
1+
# Java Inheritance - A Detailed Guide
22

3-
Java inheritance is a fundamental concept in object-oriented programming that allows classes to inherit properties and behaviors from other classes. Inheritance enables code reuse and promotes the creation of hierarchical relationships between classes.
3+
Welcome to **Codes With Pankaj**! In this tutorial, we will dive deep into **Java Inheritance**, a fundamental concept in object-oriented programming (OOP). This guide will help you understand different types of inheritance in Java, how they work, and how to use them effectively.
44

5-
In Java, inheritance is implemented using the `extends` keyword. The class that is being inherited from is called the superclass or parent class, and the class that inherits from the superclass is called the subclass or child class.
5+
## What is Inheritance in Java?
66

7-
Here's an example to illustrate the basic syntax of Java inheritance:
7+
Inheritance is one of the four pillars of OOP (along with Encapsulation, Polymorphism, and Abstraction). It allows a class (subclass/child class) to acquire the properties and behaviors of another class (superclass/parent class). This promotes code reuse and enhances maintainability.
88

9+
### Syntax of Inheritance in Java:
910
```java
10-
class Animal {
11-
protected String name;
12-
13-
public void setName(String name) {
14-
this.name = name;
15-
}
16-
17-
public void eat() {
18-
System.out.println("The animal is eating.");
19-
}
11+
class ParentClass {
12+
// Parent class properties and methods
2013
}
2114

22-
class Dog extends Animal {
23-
public void bark() {
24-
System.out.println("The dog is barking.");
25-
}
26-
}
27-
28-
public class Main {
29-
public static void main(String[] args) {
30-
Dog dog = new Dog();
31-
dog.setName("Max");
32-
dog.eat(); // Inherited method from the Animal class
33-
dog.bark(); // Method specific to the Dog class
34-
}
15+
class ChildClass extends ParentClass {
16+
// Child class properties and methods
3517
}
3618
```
3719

38-
In this example, the `Animal` class serves as the superclass, and the `Dog` class is the subclass. The `Dog` class extends the `Animal` class using the `extends` keyword. This means that the `Dog` class inherits all the members (fields and methods) of the `Animal` class.
39-
40-
The `Dog` class adds a new method `bark()`, which is specific to dogs. It can also access the `name` field and the `eat()` method from the `Animal` class because they are inherited.
20+
## Types of Inheritance in Java
21+
Java supports the following types of inheritance:
4122

42-
Inheritance supports the concept of polymorphism, which means that a subclass can be treated as an instance of its superclass. In the example above, a `Dog` object can be assigned to an `Animal` reference:
43-
44-
```java
45-
Animal animal = new Dog();
46-
```
47-
48-
This allows for flexibility and abstraction in programming, as you can work with a general type (e.g., `Animal`) while still having access to the specific behavior of the subclass (e.g., `Dog`).
49-
50-
Java supports single inheritance, which means a class can only inherit from one superclass. However, multiple levels of inheritance can be created by extending subclasses further. Additionally, Java provides the `super` keyword to access members of the immediate superclass.
51-
52-
It's important to note that not all members of a superclass are accessible in the subclass. The accessibility depends on the access modifiers used in the superclass. The `private` members are not accessible, while `public` and `protected` members can be accessed directly in the subclass.
53-
54-
Overall, Java inheritance is a powerful mechanism for code reuse and building hierarchical relationships between classes, allowing for flexibility and extensibility in object-oriented programming.
55-
56-
-----------------------------
57-
58-
## there are several types of inheritance that can be used to establish relationships between classes. The main types of inheritance in Java are:
59-
60-
**1. Single inheritance:** Java supports single inheritance, which means that a class can inherit from only one superclass. This establishes a "is-a" relationship between the classes, where the subclass is a specialized version of the superclass.
61-
62-
**2. Multilevel inheritance:** In multilevel inheritance, a class extends another class, which in turn extends another class, and so on. This creates a chain of inheritance where each subclass inherits properties and behaviors from its immediate superclass. It allows for creating a hierarchy of classes.
63-
64-
**3. Hierarchical inheritance:** Hierarchical inheritance occurs when multiple classes inherit from a single superclass. In this type of inheritance, one superclass is extended by multiple subclasses, each of which can have its own additional properties and behaviors.
65-
66-
**4. Multiple inheritance (through interfaces):** While Java doesn't support multiple inheritance of classes, it does support multiple inheritance of interfaces. An interface in Java can be implemented by multiple classes, allowing them to inherit multiple sets of methods declarations. This is known as multiple inheritance through interfaces.
67-
68-
**5. Hybrid inheritance:** Hybrid inheritance is a combination of multiple inheritance and hierarchical inheritance. It involves a mix of single and multiple inheritance, where classes inherit from multiple classes, and those classes can further be inherited by other subclasses.
69-
70-
-----------------------------
71-
72-
# 1 Single inheritance :
73-
74-
Single inheritance in Java refers to the ability of a class to inherit properties and behaviors from only one superclass. In other words, a class can extend or inherit from a single class.
75-
76-
When a class inherits from a superclass, it gains access to all the non-private members (methods and fields) of the superclass. The subclass can then add its own unique methods and fields or override the inherited ones to modify their behavior.
77-
78-
Here's an example to illustrate single inheritance in Java:
23+
### 1. **Single Inheritance**
24+
In **single inheritance**, a class inherits from only one parent class. This is the simplest form of inheritance.
7925

26+
#### Example:
8027
```java
8128
class Vehicle {
82-
protected String brand;
83-
84-
public void setBrand(String brand) {
85-
this.brand = brand;
86-
}
87-
88-
public void drive() {
89-
System.out.println("Driving the vehicle.");
29+
void start() {
30+
System.out.println("Vehicle is starting...");
9031
}
9132
}
9233

9334
class Car extends Vehicle {
94-
private int numberOfDoors;
95-
96-
public void setNumberOfDoors(int numberOfDoors) {
97-
this.numberOfDoors = numberOfDoors;
98-
}
99-
100-
public void openDoors() {
101-
System.out.println("Opening the car doors.");
102-
}
103-
}
104-
105-
public class Main {
106-
public static void main(String[] args) {
107-
Car car = new Car();
108-
car.setBrand("Toyota"); // Inherited method from Vehicle class
109-
car.setNumberOfDoors(4); // Method specific to Car class
110-
car.drive(); // Inherited method from Vehicle class
111-
car.openDoors(); // Method specific to Car class
112-
}
113-
}
114-
```
115-
116-
In this example, the `Vehicle` class is the superclass, and the `Car` class is the subclass. The `Car` class extends the `Vehicle` class using the `extends` keyword, indicating that `Car` inherits from `Vehicle`.
117-
118-
The `Car` class adds its own field `numberOfDoors` and methods `setNumberOfDoors()` and `openDoors()`. It can also access the `brand` field and the `drive()` method from the `Vehicle` class because they are inherited.
119-
120-
By using single inheritance, the `Car` class is able to inherit the common properties and behaviors defined in the `Vehicle` class while adding its own specialized features.
121-
122-
It's important to note that Java's single inheritance ensures a simpler class hierarchy and avoids the complications that can arise from multiple inheritance. However, it also means that a class can inherit from only one superclass, limiting the direct reuse of code from multiple sources.
123-
124-
125-
---------------------
126-
# 2 Multilevel inheritance :
127-
128-
Multilevel inheritance in Java refers to a scenario where a class extends another class, and that subclass is further extended by another class. This creates a chain or hierarchy of inheritance, with each subclass inheriting properties and behaviors from its immediate superclass.
129-
130-
Here's an example to demonstrate multilevel inheritance in Java:
131-
132-
```java
133-
class Animal {
134-
protected String name;
135-
136-
public void setName(String name) {
137-
this.name = name;
138-
}
139-
140-
public void eat() {
141-
System.out.println("The animal is eating.");
142-
}
143-
}
144-
145-
class Dog extends Animal {
146-
public void bark() {
147-
System.out.println("The dog is barking.");
148-
}
149-
}
150-
151-
class GermanShepherd extends Dog {
152-
public void guard() {
153-
System.out.println("The German Shepherd is guarding.");
35+
void drive() {
36+
System.out.println("Car is driving...");
15437
}
15538
}
15639

157-
public class Main {
40+
public class SingleInheritanceExample {
15841
public static void main(String[] args) {
159-
GermanShepherd dog = new GermanShepherd();
160-
dog.setName("Max");
161-
dog.eat(); // Inherited method from Animal class
162-
dog.bark(); // Inherited method from Dog class
163-
dog.guard(); // Method specific to GermanShepherd class
42+
Car myCar = new Car();
43+
myCar.start(); // Inherited method
44+
myCar.drive(); // Own method
16445
}
16546
}
16647
```
16748

168-
In this example, the `Animal` class is the superclass, the `Dog` class is the immediate subclass, and the `GermanShepherd` class is the final subclass in the chain.
169-
170-
The `Dog` class extends the `Animal` class, inheriting its `name` field and `eat()` method. It adds its own method, `bark()`, which is specific to dogs.
171-
172-
The `GermanShepherd` class further extends the `Dog` class, inheriting the `name` field, `eat()` method, and `bark()` method. It adds its own method, `guard()`, which is specific to German Shepherds.
173-
174-
By using multilevel inheritance, the `GermanShepherd` class inherits properties and behaviors from both its immediate superclass (`Dog`) and the superclass of the superclass (`Animal`). This allows for code reuse and the creation of a hierarchical relationship between classes.
175-
176-
It's important to note that multilevel inheritance should be used judiciously, as an excessively deep inheritance chain can lead to complex class relationships and potential code maintenance challenges.
177-
178-
179-
------------------------------
180-
181-
# 3 Hierarchical inheritance :
182-
183-
Hierarchical inheritance in Java refers to a situation where multiple classes inherit from a single superclass. In this type of inheritance, one superclass serves as the base class for multiple subclasses, each of which can have its own additional properties and behaviors.
184-
185-
Here's an example to illustrate hierarchical inheritance in Java:
49+
### 2. **Multilevel Inheritance**
50+
In **multilevel inheritance**, a class inherits from another class, which in turn inherits from another class, forming a chain.
18651

52+
#### Example:
18753
```java
188-
class Shape {
189-
protected String color;
190-
191-
public void setColor(String color) {
192-
this.color = color;
193-
}
194-
195-
public void draw() {
196-
System.out.println("Drawing the shape.");
54+
class Vehicle {
55+
void start() {
56+
System.out.println("Vehicle is starting...");
19757
}
19858
}
19959

200-
class Circle extends Shape {
201-
private double radius;
202-
203-
public void setRadius(double radius) {
204-
this.radius = radius;
205-
}
206-
207-
public double calculateArea() {
208-
return Math.PI * radius * radius;
60+
class Car extends Vehicle {
61+
void drive() {
62+
System.out.println("Car is driving...");
20963
}
21064
}
21165

212-
class Rectangle extends Shape {
213-
private double length;
214-
private double width;
215-
216-
public void setDimensions(double length, double width) {
217-
this.length = length;
218-
this.width = width;
219-
}
220-
221-
public double calculateArea() {
222-
return length * width;
66+
class ElectricCar extends Car {
67+
void charge() {
68+
System.out.println("Electric Car is charging...");
22369
}
22470
}
22571

226-
public class Main {
72+
public class MultilevelInheritanceExample {
22773
public static void main(String[] args) {
228-
Circle circle = new Circle();
229-
circle.setColor("Red"); // Inherited method from Shape class
230-
circle.setRadius(5.0); // Method specific to Circle class
231-
circle.draw(); // Inherited method from Shape class
232-
double circleArea = circle.calculateArea(); // Method specific to Circle class
233-
System.out.println("Circle area: " + circleArea);
234-
235-
Rectangle rectangle = new Rectangle();
236-
rectangle.setColor("Blue"); // Inherited method from Shape class
237-
rectangle.setDimensions(4.0, 6.0); // Method specific to Rectangle class
238-
rectangle.draw(); // Inherited method from Shape class
239-
double rectangleArea = rectangle.calculateArea(); // Method specific to Rectangle class
240-
System.out.println("Rectangle area: " + rectangleArea);
74+
ElectricCar myCar = new ElectricCar();
75+
myCar.start(); // Inherited from Vehicle
76+
myCar.drive(); // Inherited from Car
77+
myCar.charge(); // Own method
24178
}
24279
}
24380
```
24481

245-
In this example, the `Shape` class serves as the superclass, and both the `Circle` and `Rectangle` classes are subclasses inheriting from `Shape`.
246-
247-
The `Shape` class has a `color` field and methods `setColor()` and `draw()`. The `Circle` class extends `Shape` and adds its own `radius` field, along with methods `setRadius()` and `calculateArea()` specific to circles.
248-
249-
Similarly, the `Rectangle` class extends `Shape` and adds its own `length` and `width` fields, along with methods `setDimensions()` and `calculateArea()` specific to rectangles.
250-
251-
By using hierarchical inheritance, both the `Circle` and `Rectangle` classes inherit common properties and behaviors defined in the `Shape` class, while also having their own specialized features.
252-
253-
Hierarchical inheritance allows for code reuse and promotes the creation of a hierarchy of related classes. It enables the organization of classes into a logical structure, where common characteristics and behaviors are defined in the superclass, and specific variations are introduced in the subclasses.
254-
255-
# 4 Multiple inheritance (through interfaces) :
256-
257-
multiple inheritance of classes is not directly supported, meaning a class cannot inherit from multiple classes. However, Java does support multiple inheritance through interfaces, which allows a class to implement multiple interfaces.
258-
259-
An interface in Java is a collection of abstract methods (methods without an implementation) and constants. It defines a contract that a class must adhere to if it implements that interface. By implementing multiple interfaces, a class can inherit the method declarations from all those interfaces.
260-
261-
Here's an example to illustrate multiple inheritance through interfaces in Java:
82+
### 3. **Hierarchical Inheritance**
83+
In **hierarchical inheritance**, multiple child classes inherit from a single parent class.
26284

85+
#### Example:
26386
```java
264-
interface Flyable {
265-
void fly();
266-
}
267-
268-
interface Swimmable {
269-
void swim();
270-
}
271-
272-
class Bird implements Flyable {
273-
@Override
274-
public void fly() {
275-
System.out.println("The bird is flying.");
87+
class Vehicle {
88+
void start() {
89+
System.out.println("Vehicle is starting...");
27690
}
27791
}
27892

279-
class Fish implements Swimmable {
280-
@Override
281-
public void swim() {
282-
System.out.println("The fish is swimming.");
93+
class Car extends Vehicle {
94+
void drive() {
95+
System.out.println("Car is driving...");
28396
}
28497
}
28598

286-
class Duck implements Flyable, Swimmable {
287-
@Override
288-
public void fly() {
289-
System.out.println("The duck is flying.");
290-
}
291-
292-
@Override
293-
public void swim() {
294-
System.out.println("The duck is swimming.");
99+
class Bike extends Vehicle {
100+
void ride() {
101+
System.out.println("Bike is being ridden...");
295102
}
296103
}
297104

298-
public class Main {
105+
public class HierarchicalInheritanceExample {
299106
public static void main(String[] args) {
300-
Bird bird = new Bird();
301-
bird.fly(); // Inherited method from Flyable interface
302-
303-
Fish fish = new Fish();
304-
fish.swim(); // Inherited method from Swimmable interface
305-
306-
Duck duck = new Duck();
307-
duck.fly(); // Inherited method from Flyable interface
308-
duck.swim(); // Inherited method from Swimmable interface
107+
Car myCar = new Car();
108+
myCar.start();
109+
myCar.drive();
110+
111+
Bike myBike = new Bike();
112+
myBike.start();
113+
myBike.ride();
309114
}
310115
}
311116
```
312117

313-
In this example, there are two interfaces: `Flyable` and `Swimmable`. The `Bird` class implements the `Flyable` interface, and the `Fish` class implements the `Swimmable` interface. Each class provides an implementation for the methods declared in their respective interfaces.
314-
315-
The `Duck` class demonstrates multiple inheritance by implementing both the `Flyable` and `Swimmable` interfaces. This allows the `Duck` class to inherit the method declarations from both interfaces.
316-
317-
Through multiple inheritance with interfaces, the `Duck` class gains the ability to both fly and swim. It inherits the `fly()` method from the `Flyable` interface and the `swim()` method from the `Swimmable` interface.
318-
319-
Using interfaces for multiple inheritance allows for achieving code reuse and defining common behavior across unrelated classes. It promotes flexibility and extensibility in Java's object-oriented programming paradigm.
320-
321-
322-
# 5 Hybrid inheritance:
323-
324-
325-
Hybrid inheritance is a combination of multiple inheritance and hierarchical inheritance. It involves a mix of single and multiple inheritance, where classes inherit from multiple classes, and those classes can further be inherited by other subclasses.
326-
327-
While Java doesn't directly support hybrid inheritance, you can achieve a similar effect by utilizing a combination of interfaces and class inheritance.
328-
329-
Here's an example that demonstrates a form of hybrid inheritance in Java:
118+
### 4. **Multiple Inheritance (Using Interfaces)**
119+
Java does not support multiple inheritance with classes to avoid the **Diamond Problem**, but it allows multiple inheritance using **interfaces**.
330120

121+
#### Example:
331122
```java
332-
interface Swimmable {
333-
void swim();
123+
interface Engine {
124+
void start();
334125
}
335126

336-
class Animal {
337-
protected String name;
338-
339-
public void setName(String name) {
340-
this.name = name;
341-
}
342-
343-
public void eat() {
344-
System.out.println("The animal is eating.");
345-
}
127+
interface Transmission {
128+
void changeGear();
346129
}
347130

348-
class Dolphin extends Animal implements Swimmable {
349-
@Override
350-
public void swim() {
351-
System.out.println("The dolphin is swimming.");
131+
class Car implements Engine, Transmission {
132+
public void start() {
133+
System.out.println("Car engine starting...");
352134
}
353-
}
354-
355-
class FlyingBird {
356-
public void fly() {
357-
System.out.println("The bird is flying.");
135+
public void changeGear() {
136+
System.out.println("Car changing gears...");
358137
}
359-
}
360-
361-
class Sparrow extends FlyingBird {
362-
public void chirp() {
363-
System.out.println("The sparrow is chirping.");
138+
void drive() {
139+
System.out.println("Car is driving...");
364140
}
365141
}
366142

367-
class FlyingDolphin extends Dolphin {
368-
public void fly() {
369-
System.out.println("The flying dolphin is flying.");
370-
}
371-
}
372-
373-
public class Main {
143+
public class MultipleInheritanceExample {
374144
public static void main(String[] args) {
375-
Dolphin dolphin = new Dolphin();
376-
dolphin.setName("Flipper");
377-
dolphin.eat(); // Inherited method from Animal class
378-
dolphin.swim(); // Inherited method from Swimmable interface
379-
380-
Sparrow sparrow = new Sparrow();
381-
sparrow.fly(); // Inherited method from FlyingBird class
382-
sparrow.chirp(); // Method specific to Sparrow class
383-
384-
FlyingDolphin flyingDolphin = new FlyingDolphin();
385-
flyingDolphin.fly(); // Inherited method from Dolphin class
145+
Car myCar = new Car();
146+
myCar.start();
147+
myCar.changeGear();
148+
myCar.drive();
386149
}
387150
}
388151
```
389152

390-
In this example, there are several classes and interfaces involved:
153+
## Why Use Inheritance?
154+
### Benefits of Inheritance:
155+
- **Code Reusability** – Common methods and properties need not be rewritten in each class.
156+
- **Improved Maintainability** – Changes in the parent class automatically apply to child classes.
157+
- **Polymorphism Support** – Promotes dynamic method dispatch.
391158

392-
- The `Animal` class serves as the superclass and provides common properties and behaviors for animals.
393-
- The `Swimmable` interface declares the `swim()` method, which is implemented by the `Dolphin` class.
394-
- The `Dolphin` class extends the `Animal` class and implements the `Swimmable` interface, inheriting properties and behaviors from both the superclass and interface.
395-
- The `FlyingBird` class provides a `fly()` method for birds that can fly, which is inherited by the `Sparrow` class.
396-
- The `Sparrow` class extends the `FlyingBird` class and adds its own behavior with the `chirp()` method.
397-
- The `FlyingDolphin` class extends the `Dolphin` class, effectively combining features of a dolphin and a flying animal.
159+
## Conclusion
160+
Inheritance is a powerful feature in Java that promotes code reuse and scalability. Understanding its types and applications will help you design efficient Java programs.
398161

399-
While not a strict implementation of hybrid inheritance, this example demonstrates the idea of combining multiple inheritance and hierarchical inheritance by using a combination of class inheritance and interface implementation.
162+
For more Java tutorials, visit **[Codes With Pankaj](www.codeswithpankaj.com)**. Happy coding!
400163

401-
It's important to carefully design and consider the class hierarchy when dealing with hybrid inheritance-like scenarios to avoid complications and potential issues.

0 commit comments

Comments
 (0)
Please sign in to comment.