Unit 2: Inheritance, Interfaces, and Packages




Inheritance in Java

Inheritance allows one class to acquire the properties and methods of another class.

Simple meaning: A child class uses features of a parent class.

Real-life example:

  • Parent → Property, habits
  • Child → Inherits both

In Java:

  • Parent class → Super class
  • Child class → Sub class
  • Keyword used → extends

Super Class and Sub Class

Super Class

A super class is the class whose features are inherited.

class Animal { void eat() { System.out.println("Eating..."); } }

Sub Class

A sub class inherits the super class.

class Dog extends Animal { void bark() { System.out.println("Barking..."); } }

Key Points:

  • One class can extend only one class (single inheritance)
  • Sub class gets access to non-private members

Protected Members

The protected access modifier allows access:

  • Within the same package
  • In subclasses (even in different packages)

Example:

class Person { protected String name; }

Use:

  • Useful when data must be shared with child classes
  • More secure than public, less restrictive than private

Constructors in Sub Classes

  • Constructors are not inherited
  • Sub class constructor can call super class constructor using super()

Example:

class Parent { Parent() { System.out.println("Parent Constructor"); } } class Child extends Parent { Child() { super(); // calls parent constructor System.out.println("Child Constructor"); } }

Important Points:

  • super() must be the first statement
  • If not written, Java automatically calls parent’s default constructor

Object Class

Object is the root class of all Java classes.

Every class in Java automatically extends Object class.

Important methods of Object class:

MethodPurpose
toString()Returns string representation
equals()Compares objects
hashCode()Returns hash value
clone()Creates copy of object
finalize()Called before garbage collection

Abstract Classes and Methods

Abstract Class

An abstract class cannot be instantiated (object cannot be created).

abstract class Shape { abstract void draw(); }

Abstract Method

  • Declared without body
  • Must be implemented by subclass

class Circle extends Shape { void draw() { System.out.println("Drawing Circle"); } }

Key Points:

  • Abstract class can have:

    • Abstract methods

    • Normal methods

  • Used when partial implementation is required

Interfaces in Java

An interface is a fully abstract blueprint that contains:

  • Method declarations
  • Constants

Simple meaning: It defines what to do, not how to do.

Defining an Interface

interface Vehicle { void start(); }

Characteristics:

  • Methods are public and abstract by default
  • Variables are public, static, and final

Implementing an Interface

A class uses implements keyword to implement an interface.

class Car implements Vehicle { public void start() { System.out.println("Car starts"); } }

Key Points:

  • All interface methods must be implemented
  • Multiple interfaces can be implemented

Differences Between Class and Interface

FeatureClassInterface
Object creationPossibleNot possible
MethodsConcrete + abstractAbstract only
VariablesAny typepublic static final
InheritanceSingleMultiple
Keywordextendsimplements

Extending Interfaces

One interface can extend another interface using extends.

interface A { void show(); } interface B extends A { void display(); }

Points:

  • Interface supports multiple inheritance
  • No implementation, only declarations

Object Cloning

Object cloning means creating an exact copy of an object.

Example: Photocopy of a document

In Java:

  • Uses clone() method of Object class
  • Class must implement Cloneable interface

class Student implements Cloneable { int id; protected Object clone() throws CloneNotSupportedException { return super.clone(); } }

Types:

  • Shallow copy
  • Deep copy

Inner Classes

An inner class is a class defined inside another class.

Why use Inner Classes?

  • Better logical grouping
  • Increased security
  • Access to outer class members

Types of Inner Classes

1. Member Inner Class

class Outer { class Inner { void show() { System.out.println("Inner class"); } } }

2. Local Inner Class

Defined inside a method.

3. Anonymous Inner Class

No name, used for short implementations.

Runnable r = new Runnable() { public void run() { System.out.println("Running"); } };

4. Static Nested Class

Declared using static.

Conclusion

Inheritance, interfaces, abstract classes, and inner classes form the core structure of Java programming. They help in:

  • Code reuse
  • Security
  • Flexibility
  • Maintaining large applications

These concepts are highly important for exams, interviews, and real-world Java applications.

Packages in Java

A package in Java is a folder (directory) that is used to group related classes and interfaces together.

Simple meaning: A package is like a file folder on your computer that keeps similar files in one place.

Example:

  • All networking-related classes are stored in
    java.net

  • All input/output classes are stored in
    java.io

Defining a Package

In Java, a package is defined using the package keyword.

Syntax: package packagename;

Example:

package com.mycompany.student; public class Student { public void show() { System.out.println("Student Class"); } }

Important Rules:

  1. Package statement must be first line in source file
  2. Package name is usually written in lowercase
  3. Directory structure is automatically created by compiler

Types of Packages

1. Built-in Packages

Provided by Java itself:

  • java.lang
  • java.util
  • java.io
  • java.net
  • java.sql

2. User-Defined Packages

Created by programmers for their own applications.

CLASSPATH Setting for Packages

CLASSPATH is an environment variable that tells Java:

“Where to find user-defined classes and packages.”

Simple meaning: CLASSPATH tells Java the location of your package files.

Why CLASSPATH is Needed?

  • To run classes from different folders
  • To access external libraries (JAR files)

Setting CLASSPATH (Windows Example)

Temporary (Command Prompt):

set CLASSPATH=.;C:\MyPackages

Permanent:

  1. Right click This PC → Properties
  2. Advanced System Settings
  3. Environment Variables
  4. Add CLASSPATH

Default CLASSPATH:

  • Current directory (.)

Making JAR Files for Library Packages

What is a JAR File?

JAR (Java ARchive) is a compressed file that contains:

  • Multiple .class files
  • Package structure
  • Metadata

Simple meaning: A JAR file is like a ZIP file for Java programs.

Why Use JAR Files?

  • Easy distribution
  • Code reuse
  • Library creation
  • Faster deployment

Creating a JAR File

Step-by-Step:

  1. Compile the package:

javac com/mycompany/student/Student.java
  1. Create JAR file:

jar cf studentlib.jar com

Using JAR File:

java -cp studentlib.jar;. TestClass

Import Statement

The import statement allows access to classes of a package without writing full package name.

Types of Import

1. Single Class Import

import java.util.Scanner;

2. Whole Package Import

import java.util.*;

Without Import:

java.util.Scanner sc = new java.util.Scanner(System.in);

Important Notes:

  • java.lang is imported automatically
  • Import does not increase program size

Static Import

Static import allows access to static members of a class without class name.

Example Without Static Import:

Math.sqrt(25);

With Static Import:

import static java.lang.Math.*; sqrt(25);

Benefits:

  • Cleaner code
  • Useful for constants and utility methods

Naming Convention for Packages

Java follows standard naming conventions for packages.

Rules:

  1. Always use lowercase letters
  2. Use reverse domain name

Example:

OrganizationPackage Name
Googlecom.google.project
Oraclecom.oracle.database
College Projectin.ac.college.project

Benefits:

  • Avoids name conflicts
  • Easy identification
  • Industry standard

Networking: java.net Package

The java.net package provides classes for network programming.

Meaning: It helps Java programs communicate over the internet or network.

Important Classes in java.net

ClassPurpose
URLRepresents web address
URLConnectionConnects to URL
SocketClient-side communication
ServerSocketServer-side communication
InetAddressIP address handling
DatagramSocketUDP communication

Example: URL Class

import java.net.*; class TestURL { public static void main(String args[]) throws Exception { URL url = new URL("https://www.google.com"); System.out.println(url.getHost()); } }

Uses of java.net

  • Client-server applications
  • Chat applications
  • File transfer
  • Web services

Conclusion

Packages in Java help to:

  • Organize large programs
  • Improve code reusability
  • Avoid naming conflicts
  • Support modular development

Understanding package creation, CLASSPATH, JAR files, import statements, and networking packages is essential for real-world Java development.