Detailed Unit II Inheritance Interface Packages
Detailed Unit II Inheritance Interface Packages
2.1 Inheritance
the properties and behaviors (fields and methods) of another class (superclass/parent class). This
Types of Inheritance:
1. Single Inheritance:
Example:
class Animal {
2. Multilevel Inheritance:
Example:
class Animal { void eat() { System.out.println("Eating..."); } }
3. Hierarchical Inheritance:
Example:
Method Overriding:
- When a subclass provides a specific implementation of a method already defined in its superclass.
- Example:
@Override
}
Animal a = new Dog();
Final Keyword:
- Example:
class Animal {
Dog() {
System.out.println("Dog Constructor");
@Override
void sound() {
super.sound(); // Calls superclass method
System.out.println("Bark");
- Example:
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.
- Example:
interface Animal {
void sound();
}
System.out.println("Bark");
Extending Interfaces:
- Example:
2.3 Packages
A package in Java is a namespace that organizes classes and interfaces. It helps avoid name
package com.example;
Accessing Packages:
- Classes and interfaces from packages can be accessed using the 'import' statement.
Import Statement:
Static Import: