Unit 4: Inheritance & Packaging
A comprehensive guide on Java Inheritance & Packaging for BCA 3rd Semester students. Learn the ‘extends’ keyword, super keyword, method overriding, dynamic dispatch, abstract & final classes, and interfaces with practical examples.
In this unit, we'll cover the fundamental concepts of Inheritance, Packaging, and Interfaces in Java. These concepts are crucial for organizing and structuring Java programs efficiently. We'll look at both theoretical concepts and practical examples.
Inheritance in Object-Oriented Programming (OOP) is a mechanism that allows a new class (called a subclass or child class) to acquire the properties (fields) and behaviors (methods) of an existing class (called a superclass or parent class). This allows code reusability and establishes a relationship between the parent and child classes.
In simple terms, inheritance enables a subclass to inherit and extend the functionality of its superclass.
Key Points of Inheritance in OOP:
-
Subclass (Child Class): The class that inherits from another class.
-
Superclass (Parent Class): The class whose properties and methods are inherited by the subclass.
-
Code Reusability: Inheritance allows the child class to reuse the code of the parent class without having to rewrite it.
-
Extending Functionality: The child class can also add its own specific fields and methods or override inherited methods.
-
"IS-A" Relationship: The subclass is a type of the superclass. For example, a Dog is an Animal.
Benefits of Inheritance:
-
Code Reusability: Inherited methods can be reused, reducing duplication of code.
-
Hierarchical Class Structure: It helps in organizing and structuring the code in a natural way.
-
Extensibility: New features or behaviors can be added to subclasses without modifying existing code in the superclass.
1.1 The extends
Keyword
In Java, a subclass is created by using the extends
keyword. This allows the subclass to inherit the fields and methods of the superclass.
Syntax
class Subclass extends Superclass {
// Additional fields and methods
}
Example:
// Superclass (Parent Class)
class Vehicle {
// Method of Vehicle class
void start() {
System.out.println("The vehicle is starting.");
}
void stop() {
System.out.println("The vehicle is stopping.");
}
}
// Subclass (Child Class)
class Car extends Vehicle {
// Method of Car class
void honk() {
System.out.println("The car honks the horn.");
}
// Overriding the start method of Vehicle class
@Override
void start() {
System.out.println("The car is starting with a roar.");
}
}
public class Main {
public static void main(String[] args) {
// Creating an object of Car class
Car myCar = new Car();
// Calling methods of Car and Vehicle
myCar.start(); // Calls the overridden start() method in Car class
myCar.stop(); // Inherited method from Vehicle class
myCar.honk(); // Method of Car class
}
}
Conclusion:
-
The
Car
class inherits the common behavior of a vehicle (such asstart()
andstop()
), but also adds its own specific behavior (honk()
). -
We used method overriding to change the behavior of the
start()
method in theCar
class. -
The
Car
class inherits thestart()
andstop()
methods fromVehicle
, so we didn't need to define them again.
1.3 The super
Keyword
The super
keyword is used to refer to the superclass. It can be used to:
-
Access superclass methods.
-
Call the superclass constructor.
Example:
class Animal {
Animal() {
System.out.println("Animal constructor called");
}
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
Dog() {
super(); // Calls the Animal class constructor
System.out.println("Dog constructor called");
}
void bark() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
}
}
1.4 Overriding Methods
When a subclass provides its own version of a method that is already defined in the superclass, it is called method overriding.
-
The overriding method in the subclass should have the same name, return type, and parameters as the method in the superclass.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Animal();
Dog d = new Dog();
a.sound(); // Calls Animal's method
d.sound(); // Calls Dog's overridden method
}
}
1.5 Dynamic Method Dispatch
Java supports dynamic method dispatch, which means that the method that is called is determined at runtime. This happens when a subclass object is referred to by a superclass reference.
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog(); // Animal reference, but Dog object
a.sound(); // Calls Dog's method at runtime
}
}
1.7 Abstract and Final Classes
-
Abstract Classes: These are classes that cannot be instantiated on their own. They can have abstract methods (methods without a body) that must be implemented by subclasses.
-
Final Classes: A class declared as
final
cannot be subclassed.
Example:
abstract class Animal {
abstract void sound(); // Abstract method
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}
Example
final class Car {
void drive() {
System.out.println("Car is driving");
}
}
// Error: Cannot subclass a final class
// class ElectricCar extends Car { }
2. Packages in Java
A package is a way to group related classes and interfaces into namespaces. This helps in avoiding class name conflicts and organizing code logically.
2.1 Defining a Package
You define a package at the very beginning of a Java source file using the package
keyword.
Example:
package com.company;
class Employee {
String name;
Employee(String name) {
this.name = name;
}
void display() {
System.out.println("Employee Name: " + name);
}
}
2.2 Importing a Package
To use a class from another package, you need to import it.
Example:
import com.company.Employee;
public class Main {
public static void main(String[] args) {
Employee e = new Employee("John");
e.display();
}
}
2.3 Access Control in Packages
-
Public: A class, method, or field that is marked as
public
can be accessed from any other class. -
Private: A method or field marked as
private
can only be accessed within its own class. -
Protected: A
protected
member can be accessed within its own package and by subclasses. -
Default: If no access modifier is provided, the member has package-private access.
3. Interfaces in Java
An interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields.
3.1 Defining an Interface
An interface is defined using the interface
keyword. All methods in an interface are abstract by default.
Example:
interface Animal {
void sound(); // Abstract method
}
class Dog implements Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound(); // Calls Dog's implementation
}
}
3.2 Implementing an Interface
A class implements an interface using the implements
keyword. The class must provide implementations for all methods declared in the interface.
3.3 Applying Interfaces
Interfaces can be used to achieve multiple inheritance in Java, as a class can implement multiple interfaces.
Example:
interface Animal {
void sound();
}
interface Domestic {
void pet();
}
class Dog implements Animal, Domestic {
@Override
public void sound() {
System.out.println("Dog barks");
}
@Override
public void pet() {
System.out.println("Dog is a pet");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // Calls Dog's sound method
d.pet(); // Calls Dog's pet method
}
}
Possible Questions:
-
Explain the concept of inheritance in Java. Illustrate with an example including the use of
extends
andsuper
keywords. -
Describe method overriding and dynamic method dispatch. How does Java determine which version of the method to call at runtime?
-
Discuss the
Object
class in Java. Mention any four methods provided by it with their purposes. -
Explain how packages are created and imported in Java. Discuss access specifiers in the context of packages.
-
Define an interface. Write a program that defines and implements an interface. Also explain how multiple inheritance is achieved using interfaces.
- What are access specifiers in Java packages?Explain them.
- Differentiate between superclass and subclass with examples.