0% found this document useful (0 votes)
8 views12 pages

Java Inheritance Explained: Concepts & Types

Copyright
© All Rights Reserved
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
0% found this document useful (0 votes)
8 views12 pages

Java Inheritance Explained: Concepts & Types

Copyright
© All Rights Reserved
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

Inheritance and interface

23 September 2025 21:08

🧬 INHERITANCE IN JAVA – Detailed Notes


What Is Inheritance?
• Inheritance is the process by which one class acquires the properties and behaviors (fields and
methods) of another class.
• Promotes code reuse, modularity, and hierarchical classification.

Advantages of Inheritance from the textbook:


• ✅ Code Reusability: You can reuse existing code from parent classes.
• 🧩 Clear Structure: It creates a logical, easy-to-understand class hierarchy.
• 🛠 Easy Maintenance: Code is organized into parent and child classes.
• 🚀 Quick Start: No need to write everything from scratch—extend existing classes.
• 📈 Scalability: Small systems can grow into large ones smoothly.
• 🧠 Real-World Modeling: Inheritance helps represent objects and relationships naturally.

Terminology
Term Meaning
Superclass The parent/base class
Subclass The child/derived class
extends Keyword used to inherit a class

🔑 What Does extends Mean?


• The extends keyword is used to create a subclass that inherits from a superclass.
• It allows the new class to reuse and extend the functionality of an existing class.
• Syntax:
class SubClassName extends SuperClassName {
// additional members and methods
}

📘 Textbook Example Breakdown


class Calculation {
int z;
public void addition(int x, int y) { ... }
public void Subtraction(int x, int y) { ... }
}
public class My_Calculation extends Calculation {
public void multiplication(int x, int y) { ... }
public static void main(String args[]) {
My_Calculation demo = new My_Calculation();
[Link](20, 10); // inherited from Calculation
[Link](20, 10); // inherited from Calculation
[Link](20, 10); // defined in My_Calculation

java chp3 Page 1


[Link](20, 10); // defined in My_Calculation
}
}
• ✅ My_Calculation inherits addition() and Subtraction() from Calculation.
• ✅ It adds its own method multiplication().
• ✅ This demonstrates code reuse, hierarchical structure, and modularity.

🚫 Important Rule
• Java does not support multiple inheritance directly using extends. A class can only extend one
superclass.

Types of Inheritance in Java


Single Inheritance
• ✅ Simplifies Design: Ideal for straightforward relationships like Vehicle → Car.
• 🧠 Best for Beginners: Easy to understand and implement.
• 🔍 Use Case: When one class logically extends another without needing multiple layers.
• 📌 Limitation: Doesn’t scale well for complex hierarchies.

Mul level Inheritance


• 🏗 Layered Extension: Each class builds upon the previous one.
• 🔄 Chain of Responsibility: Useful when behavior needs to evolve step-by-step.
• 🧬 Inheritance Depth: Can go as deep as needed (A → B → C → D).
• ⚠ Cau on: Deep chains can become hard to debug and maintain.

Hierarchical Inheritance
• 🌳 Shared Base Class: Multiple subclasses inherit from one superclass.
• 🧩 Code Reuse Across Branches: Common logic in superclass benefits all children.
• 🧠 Real-World Modeling: Think Student → Medical, Engineering, Arts.
• 🔄 Combines with Multilevel: Can nest deeper levels within branches.

🚫 Why Java Doesn’t Support Multiple Inheritance (Directly)


• ❌ Ambiguity Problem: If two superclasses have the same method, which one should the
subclass inherit?
• ✅ Solution: Java uses interfaces to simulate multiple inheritance safely.

🧪 Bonus: Interface-Based Inheritance


• 🔗 Multiple Interfaces: A class can implement multiple interfaces.
• 🧠 Polymorphism-Friendly: Promotes flexible design and decoupling.
• 📌 Example:
interface Printable { void print(); }
interface Scannable { void scan(); }

class MultiFunctionPrinter implements Printable, Scannable {


public void print() { ... }
public void scan() { ... }
}

java chp3 Page 2


}

Type Description Example


Single Inheritance One subclass inherits one superclass class A → class B extends
A
Multilevel Inheritance Chain of inheritance A→B→C
Hierarchical Multiple subclasses inherit one superclass A → B, C
Inheritance
Multiple Inheritance ❌ Not supported with classes (only via —
interfaces)
📌 Java avoids multiple inheritance with classes to prevent ambiguity (Diamond Problem).

🧬 Superclass & Subclass


• A superclass (also called base or parent class) defines common properties and behaviors.
• A subclass (also called derived or child class) inherits from the superclass and can:
○ Reuse its members (fields and methods)
○ Add new members
○ Override existing behavior
🔗 Syntax:
class SubclassName extends SuperclassName {
// additional members or overrides
}
📌 Example:
class Vehicle {
int registrationNumber;
Person owner;
void transferOwnership(Person newOwner) { ... }
}
class Car extends Vehicle {
int numberOfDoors;
}

🧠 Use of super Keyword


The super keyword refers to the immediate superclass and is used in two main ways:
Calling Superclass Constructor
• Used in subclass constructor to invoke superclass constructor.
• Must be the first statement in the subclass constructor.
class Primary {
int cal;
Primary(int a) { cal = a; }
}
class Secondary extends Primary {
int cal;
Secondary(int x, int y) {
super(y); // calls Primary constructor

java chp3 Page 3


super(y); // calls Primary constructor
cal = x;
}
}
Accessing Hidden Members
• If subclass defines a member with the same name as in superclass, use [Link] to
access the superclass version.
class SuperClass {
int n;
}
class Subclass extends SuperClass {
int n;
Subclass(int x, int y) {
super.n = [Link](x, y);
n = [Link](x, y);
}
void display() {
[Link]("SuperClass n = " + super.n);
[Link]("Subclass n = " + n);
}
}
🔄 Method Overriding
• If a subclass overrides a method from the superclass, [Link]() can be used to call the
original version.

🏗 Class Hierarchies
• Subclasses can form multi-level inheritance chains.
• Multiple subclasses can share the same superclass (hierarchical inheritance).
• Example: Vehicle → Car, Truck, Motorcycle — all share common features but add their own.

Here’s a concise and clear explanation of Method Overriding and Runtime Polymorphism in Java, based
on the textbook Object Oriented Programming Using Java - I:

🔁 Method Overriding
• Definition: When a subclass defines a method with the same signature (name, parameters, return
type) as a method in its superclass, it overrides the superclass method.
• Purpose: To provide a specific implementation in the subclass that replaces the generic one in the
superclass.
✅ Rules:
1. Method signature must match exactly.
2. Access level can be widened (e.g., protected → public), but not narrowed.
3. Only inherited methods can be overridden (not constructors or private methods).

🧠 Runtime Polymorphism
• Definition: The decision of which method to invoke is made at runtime, not at compile time.
• Achieved Through: Method overriding + superclass reference pointing to subclass object.
📌 Example:
class Bank {

java chp3 Page 4


class Bank {
int getRateOfInterest() { return 0; }
}
class HDFC extends Bank {
int getRateOfInterest() { return 8; }
}
class ICICI extends Bank {
int getRateOfInterest() { return 7; }
}
class SBI extends Bank {
int getRateOfInterest() { return 9; }
}
🖨 Output:
Bank b = new HDFC();
[Link]([Link]()); // Output: 8
Even though b is of type Bank, the method from HDFC is called—this is runtime polymorphism.

🧩 Use of super Keyword


• Used to call the superclass version of an overridden method.
• Example:
class Animal {
void move() { [Link]("Animals can move"); }
}
class Cat extends Animal {
void move() {
[Link](); // calls Animal's move()
[Link]("Cats can Walk and Run");
}
}

Final Keyword
What Does final Mean?
The final keyword is used to declare constants, non-overridable methods, and non-inheritable classes.
Once something is marked final, it cannot be changed or extended.

📌 Usage of final in Java


Context Effect Example Syntax
Variable Value cannot be changed after initialization final int PI = 3.14;
Method Cannot be overridden in a subclass public final void show() { ... }
Class Cannot be extended or subclassed final class MyClass { ... }

final Keyword with Variables


• Declaring a variable with final means its value cannot be changed once assigned.
• It becomes a constant in the program.

java chp3 Page 5


✅ Syntax:
java
final datatype variableName;
📌 Example:
java
final double PI = 3.14;
• PI is now a constant—any attempt to reassign it will cause a compile-time error.

🔐 final Keyword with Methods


• Declaring a method as final means it cannot be overridden by any subclass.
• This is useful when you want to lock down behavior that should remain unchanged across
inheritance.

✅ Syntax:
access_specifier final return_type methodName(arguments) {
// method body
}

📌 Example from Program 3.10:


class A {
final void meth() {
[Link]("This is a final method.");
}
}
class B extends A {
void meth() { // ❌ Compile-time error: Cannot override final method
[Link]("Illegal!");
}
}

🧠 Why Use Final Methods?


• ✅ To protect critical logic from being altered.
• ✅ To enforce consistent behavior across subclasses.
• ✅ To prevent accidental overrides in large or collaborative projects.

final Keyword with Classes


• Declaring a class as final means it cannot be extended or subclassed.
• This is useful when you want to lock the class structure and prevent inheritance.
✅ Syntax:
java
final class ClassName {
// members and methods
}
📌 Example:
java
final class FinalClass {
void show() {

java chp3 Page 6


void show() {
[Link]("Hello from FinalClass");
}
}
class ErrorClass extends FinalClass { // ❌ Compile-time error
void show() {
[Link]("Trying to override");
}
}
🚫 Output:
Code
Error: Cannot inherit from final class FinalClass

🧠 Why Use Final Classes?


• ✅ To protect core logic from being altered via inheritance.
• ✅ To enforce immutability in design (especially in utility or security-related classes).
• ✅ To optimize performance in some cases, as final classes allow certain compiler optimizations.

🧠 What Is Abstraction?
• Abstraction means hiding implementation details and showing only essential features.
• It helps focus on what an object does, not how it does it.

🔐 Abstract Classes
• Declared using abstract class ClassName.
• Can contain both abstract methods (no body) and concrete methods (with body).
• Cannot be instantiated directly.
• Must be extended by a subclass to provide method definitions.
✅ Syntax:
abstract class Shape {
abstract void area(); // abstract method
void display() {
[Link]("Non-abstract method");
}
}

✍ Abstract Methods
• Declared with abstract keyword and no body.
• Must be implemented in the subclass.
• Cannot be final or static.
✅ Syntax:
abstract void area();

📊 Class vs Abstract Class


Feature Class Abstract Class
Object creation Allowed Not allowed
Method types Only concrete methods Abstract + concrete methods

java chp3 Page 7


Method types Only concrete methods Abstract + concrete methods
Extension requirement Optional Mandatory
Declaration class ClassName {} abstract class ClassName {}

🧪 Example: Program 3.12


abstract class Shape {
double pi = 3.14;
abstract void area();
void display() {
[Link]("Non-abstract method of Shape");
}
}
class Rectangle extends Shape {
int l, b;
Rectangle(int x, int y) { l = x; b = y; }
void area() {
[Link]("Area = " + (l * b));
}
}
class Circle extends Shape {
double r;
Circle(double x) { r = x; }
void area() {
[Link]("Area = " + (pi * r * r));
}
}
🖨 Output:
Area of Rectangle: 50
Area of Circle: 19.625

🧠 Runtime Polymorphism with Abstract Classes


Shape s = new Circle(2.5);
[Link](); // Calls Circle's implementation
This shows runtime polymorphism—the method call is resolved at runtime based on the actual object.

🧩 INTERFACE IN JAVA – Detailed Notes


\🧩 What Is an Interface?
• An interface is a blueprint for a class—it defines what a class should do, but not how.
• It contains:
○ Abstract methods (no body)
○ Static constants (final by default)

🔑 Key Features
Feature Description
Abstraction Interfaces provide 100% abstraction—no implementation, just declarations.
Multiple A class can implement multiple interfaces, solving Java’s single inheritance

java chp3 Page 8


Multiple A class can implement multiple interfaces, solving Java’s single inheritance
Inheritance limitation.
Method Visibility All interface methods are implicitly public and abstract.
Constants Variables in interfaces are public, static, and final by default.
No Method Bodies Interfaces do not implement methods—only declare them.

✅ Syntax Example
interface Drawable {
int MAX_SIZE = 100; // constant
void draw(); // abstract method
}
class Circle implements Drawable {
public void draw() {
[Link]("Drawing Circle");
}
}

🧠 Why Use Interfaces?


• To enforce a contract: any class that implements the interface must define its methods.
• To decouple design: allows flexibility in how functionality is implemented.
• To simulate multiple inheritance: a class can implement multiple interfaces unlike extending
multiple classes.

Run me Polymorphism via Interface


Drawable d = new Circle();
[Link](); // Output: Drawing Circle

🧩 What Is an Interface?
• An interface is a contract or blueprint that defines what a class must do, but not how.
• It contains:
○ Abstract methods (no body)
○ Constants (public, static, final by default)
• Interfaces help achieve full abstraction and support multiple inheritance.

🔑 Syntax of an Interface
access_specifier interface InterfaceName {
// constants
type CONSTANT_NAME = value;
// abstract methods
returnType methodName(parameters);
}
📌 Example:
interface conversions {
double GM_TO_KG = 1000;
double CM_TO_FT = 30;

java chp3 Page 9


double CM_TO_FT = 30;
double gmtokg(double gm);
double cmtoft(double cm);
double kgtogm(double kg);
double fttocm(double ft);
}

🔄 Class vs Interface – Key Differences


Feature Class Interface
Method definitions Can have both abstract and concrete Only method declarations (no
methods bodies)
Inheritance Extended by another class Implemented by classes
Object creation Objects can be created Cannot instantiate interfaces
Variables Can be final or non-final Always final, static, and public
Multiple Not supported Supported via interfaces
inheritance
Syntax class ClassName {} interface InterfaceName {}

🧠 Why Use Interfaces?


• ✅ To enforce a consistent structure across multiple classes.
• ✅ To simulate multiple inheritance safely.
• ✅ To separate what a class should do from how it does it.

🧩 What Is Interface Implementation?


• Once an interface is defined, any class can implement it using the implements keyword.
• The class must provide definitions for all abstract methods declared in the interface.

✅ Syntax
access_specifier class ClassName implements InterfaceName {
// method definitions
}

📘 Program 3.14 Breakdown


🔹 Interface Definition
interface conversions {
double GM_TO_KG = 1000;
double gmtokg(double gm);
double kgtogm(double kg);
}
• GM_TO_KG is a constant.
• Two abstract methods: gmtokg() and kgtogm().

🔹 Class Implementation
class Convert implements conversions {
public double gmtokg(double gm) {

java chp3 Page 10


public double gmtokg(double gm) {
return gm / GM_TO_KG;
}
public double kgtogm(double kg) {
return kg * GM_TO_KG;
}
}
• Convert class provides concrete definitions for both methods.

🔹 Main Class
class ImplIface1 {
public static void main(String args[]) {
Convert ConvObj = new Convert();
conversions c;
c = ConvObj;
[Link]("2000 gm = " + [Link](2000) + " kg");
[Link]("50 kg = " + [Link](50) + " gm");
}
}
• Demonstrates runtime polymorphism: conversions c = ConvObj;
• Interface reference c calls methods implemented in Convert.

🖨 Output
2000 gm = 2.0 kg
50 kg = 50000.0 gm

🧠 Key Takeaways
• Interfaces define what a class should do.
• Classes that implement interfaces must define how it’s done.
• Interfaces support multiple inheritance and polymorphism.

🏷 Marker Interface in Java


🔹 Definition
• A marker interface is an empty interface—no methods, fields, or constants.
• It acts as a tag or signal to the JVM or compiler to apply special behavior to the class.
🔹 Purpose
• Provides runtime metadata about a class.
• Used when static type information is needed but no behavior is defined.
🔹 Examples
Interface Package Purpose
Serializable [Link] Enables object serialization (saving object state to file/stream).
Cloneable [Link] Allows object cloning via [Link]() method.
Remote [Link] Marks objects for remote method invocation across JVMs.

🔹 Analogy
Think of a marker interface like a VIP badge at an event. It doesn’t do anything itself, but it tells

java chp3 Page 11


Think of a marker interface like a VIP badge at an event. It doesn’t do anything itself, but it tells
the staff (JVM/compiler) to treat the person (class) differently.
🔹 Declaration Example
public interface Serializable {
// No methods
}

🧠 Functional Interface in Java


🔹 Definition
• A functional interface has exactly one abstract method.
• Can have default or static methods, but only one abstract method is allowed.
🔹 Purpose
• Enables lambda expressions and method references.
• Core to functional programming in Java (introduced in Java 8).
🔹 Examples
Interface Abstract Method Use Case
Runnable run() Thread execution logic.
Comparable<T> compareTo(T o) Object comparison for sorting.
ActionListener actionPerformed(ActionEvent e) GUI event handling.

🔹 Declaration Example
@FunctionalInterface
public interface MyFunction {
int apply(int x);
}
🔹 Lambda Usage
MyFunction square = x -> x * x;
[Link]([Link](5)); // Output: 25

java chp3 Page 12

You might also like