Unit II: Inheritance, Interface, and Packages
2.1 Inheritance
Inheritance is a mechanism in object-oriented programming that allows a class (subclass) to inherit
properties and behaviors
(fields and methods) from another class (superclass). This promotes code reuse and establishes a
relationship between classes.
Types of Inheritance:
1. Single Inheritance: A subclass inherits from one superclass.
2. Multilevel Inheritance: A class inherits from a subclass, forming a hierarchy.
3. Hierarchical Inheritance: Multiple classes inherit from the same superclass.
Method Overriding:
- When a subclass provides a specific implementation of a method already defined in its superclass.
Final Keyword:
- Final Variables: Constants that cannot be modified once initialized.
- Final Methods: Methods that cannot be overridden by subclasses.
The 'super' Keyword:
- Used to access superclass methods and constructors.
Abstract Methods and Classes:
- Abstract Class: Cannot be instantiated and may contain abstract methods.
- Abstract Method: Declared without implementation, must be implemented by subclasses.
2.2 Interfaces
An interface in Java is a reference type, similar to a class, that can contain only abstract methods,
static methods,
and final variables. Interfaces specify what a class must do but not how it does it.
Defining and Implementing Interfaces:
- An interface is defined using the 'interface' keyword.
- A class implements an interface using the 'implements' keyword.
Accessing Interface Variables and Methods:
- Interface variables are public, static, and final by default.
- Methods in an interface are abstract by default.
Extending Interfaces:
- An interface can extend another interface using the 'extends' keyword.
2.3 Packages
A package in Java is a namespace that organizes classes and interfaces. It helps avoid name
conflicts and enhances modularity.
Types of Packages:
1. Built-in Packages: Provided by Java (e.g., [Link], [Link]).
2. User-defined Packages: Created by developers.
Naming and Creating Packages:
- A package is declared using the 'package' keyword at the top of the Java source file.
Accessing Packages:
- Classes and interfaces from packages can be accessed using the 'import' statement.
Import Statement:
- 'import [Link];' or 'import package.*;' to import specific classes or all classes from a
package.
Static Import:
- Allows access to static members of a class directly without class reference (e.g., 'import static
[Link].*').
Adding Classes and Interfaces to a Package:
- New classes and interfaces can be added by placing the source files in the package directory and
compiling them.