Java Programming
SCCPC21
UNIT - 2
Overview Of Unit - 2
Inheritance :
• Basic Concepts Packages :
Exception Handling :
• Types of Inheritance • Definition
• Try - catch - throw
• member access rules • Access Protection
• Throws
• Usage of this and Super key word • Importing Packages
• finally
• Method Overloading Interface:
• Built - in Exceptions
• Method Overriding • Definition
• Creating Own Exception
• Abstract classes • Implementation
Classes.
• Dynamic Method dispatch • Extending Interfaces.
• Usage Of Final keyword
• RecommendedTexts
1. Herbert Schildt, The Complete Reference, Tata McGraw Hill, New Delhi, 7th Edition, 2010.
2. Gary Cornell, Core Java 2 Volume I – Fundamentals, Addison Wesley, 1999.
• ReferenceBooks
1. Head First Java, O‟Rielly Publications.
2. Y. Daniel Liang, Introduction to Java Programming, 7th Edition, Pearson Education India, 2010.
INHERITANCE
Basic Concepts of Inheritance
Inheritance in Object-Oriented Programming (OOP) lets a new class (subclass) inherit properties (data/methods)
from an existing class (superclass), promoting code reuse and establishing "is-a" relationships, with common types
being Single, Multilevel, Hierarchical, Multiple (via interfaces in Java), and Hybrid, combining others.
INHERITANCE
Basic Concepts of Inheritance
• Super Class / Parent Class /Base Class : The class whose properties are inherited (e.g., Animal).
• Sub Class / Child Class / Derived Class : The class that inherits from the superclass (e.g., Dog).
• Code Reusability : Avoids duplicating common code in multiple classes.
• Polymorphism : Allows subclasses to override methods for unique behavior.
Types of Inheritance
1. Single Inheritance : One subclass inherits from one superclass (A -> B).
⚬ Example: Dog inherits from Animal.
[Link] Inheritance : A chain of inheritance (A -> B -> C).
⚬ Example: Vehicle -> Automobile -> Car.
[Link] Inheritance : Multiple subclasses inherit from a single superclass (A -> B, A -> C).
⚬ Example: Chinese Restaurant, Italian Restaurant inherit from Restaurant.
[Link] Inheritance : A class inherits from multiple super classes (A + B -> C).
Example: Think of a Multitool that has functions from a Hammer, Screwdriver, and Pliers
1. Hybrid Inheritance : A combination of two or more types (e.g., Multilevel + Multiple).
Example: Inheriting give_birth() from Mammal (Multilevel) and lay_eggs() from Bird, plus speak() from
Animal.
INHERITANCE
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and behavior of a
single-parent class. Sometimes, it is also known as simple inheritance.
INHERITANCE
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also acts as
the base class for other classes.
INHERITANCE
3. Hierarchical Inheritance
When two or more child classes inherit from the same parent class, it is called hierarchical inheritance.
INHERITANCE
4. Multiple Inheritance
Multiple inheritance means a single child class inherits from more than one parent class.
Important (Java):
• Java does NOT support multiple inheritance using classes (to avoid ambiguity), but it supports multiple
inheritance using interfaces.
Interface
• An interface in Java is a blueprint of a class. Interface cannot create objects
• It contains method declarations only, not method bodies.
• It tells a class what to do, not how to do.
Real-life Example
• Interface → Remote (buttons only)
• Class → TV (actual working)
INHERITANCE
5. Hybrid Inheritance
(Combination of Hierarchical + Multiple Inheritance)
Hybrid inheritance is a combination of two or more types of
inheritance, such as:
• Single
• Multilevel
• Hierarchical
• Multiple
In Java:
Hybrid inheritance is not supported using classes, but it can
be achieved using interfaces.
Easy Explanation
• A & B → Interfaces (Multiple inheritance)
• C → Implements A and B
• D → Extends C (Multilevel inheritance)
This mix is called Hybrid Inheritance.
Member Access Rule
In Java, member access is controlled by four access modifiers, which define the visibility and scope of classes,
methods, and variables.
The four access levels, from most restrictive to least restrictive, are:
• private: Members declared as private are only accessible within the same class where they are declared. They
are useful for data encapsulation and hiding internal implementation details.
• default (package-private): If no access modifier is specified, the member has default access. This allows access
to any other class within the same package, but not from outside that package.
• protected: Members with protected access are accessible within the same package, and also by all subclasses,
even if the subclasses are in a different package.
• public: The public modifier provides the widest scope, meaning the member can be accessed from any other
class, in any package.
One-line Definitions
• private → Accessible only within the same class
• default → Accessible within the same package
• protected → Accessible within same package and subclasses
• public → Accessible everywhere
Member Access Rule Example code using 4 types of access specifiers
Usage of this and Super key word
When working with Java classes, two important keywords, this and super, help in handling instance variables and
inheritance. In this blog, we will understand these keywords with explanations and examples.
What is this Keyword?
The this keyword refers to the current instance of a class. It is mainly used to differentiate between instance
variables and parameters with the same name, invoke constructors within the same class, and pass the current
instance to a method.
Uses of this Keyword
• Referring to instance variables
• Calling another constructor in the same class
• Passing the current object as a parameter
• Returning the current instance from a method
Usage of this and Super key word
What is super Keyword?
The super keyword is used in inheritance to refer to the parent class. It is mainly used to access parent class
members, invoke parent class methods, and call parent class constructors.
Uses of super Keyword
• Accessing parent class methods
• Calling the parent class constructor
• Accessing parent class variables
this VS Super
Method Overloading and Method Overriding
Polymorphism
The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph
(forms), this means one entity can take many forms. In Java, polymorphism allows the same method or object to
behave differently based on the context, specially on the project's actual runtime class.
Types of Polymorphism
Polymorphism in Java is mainly of 2 types as mentioned below:
• Method Overloading
• Method Overriding
Review of Object Oriented concepts
Method Overloading and Method Overriding
1. Method Overloading: Also, known as compile-time polymorphism, is the concept of Polymorphism where more
than one method share the same name with different signature(Parameters) in a class. The return type of these
methods can or cannot be same.
2. Method Overriding: Also, known as run-time polymorphism, is the concept of Polymorphism where method in the
child class has the same name, return-type and parameters as in parent class. The child class provides the
implementation in the method already written.
Advantage of OOPs over Procedure-Oriented Programming Language
Object-oriented programming (OOP) offers several key advantages over procedural programming:
• By using objects and classes, you can create reusable components, leading to less duplication and more
efficient development.
• It provides a clear and logical structure, making the code easier to understand, maintain, and debug.
Disadvantages of OOPs
• OOP has concepts like classes, objects, inheritance etc. For beginners, this can be confusing and takes time to
learn.
• If we write a small program, using OOP can feel too heavy. We might have to write more code than needed just
to follow the OOP structure.
Review of Object Oriented concepts
Method Overloading Method Overriding
Abstract classes
Abstraction
Abstraction in Java is the process of hiding the
implementation details and only showing the essential
details or features to the user. It allows to focus on what
an object does rather than how it does it. The
unnecessary details are not displayed to the user.
Note : In Java, abstraction is achieved by interfrace and
abstract class. We can achieve 100% abstraction using
interfaces.
Easy Explanation
• Animal is abstract, so we cannot create its object
• Dog provides implementation of the abstract
method
• Abstract class supports dynamic method dispatch
Dynamic Method Dispatch in Java
Introduction
Dynamic Method Dispatch, also known as Runtime Polymorphism, is one of the most powerful concepts in Java's
object-oriented programming. It allows Java to determine which method to invoke at runtime rather than compile
time. This feature is fundamental in achieving method overriding and is widely used in real-world applications.
Understanding Dynamic Method Dispatch
In Java, method calls are resolved dynamically at runtime using Dynamic Method Dispatch. This mechanism
enables a superclass reference variable to refer to a subclass object, and Java determines which overridden
method to execute based on the actual object type.
Key Points:
• It enables runtime polymorphism.
• Method invocation is determined by the object that the reference variable refers to (not the type of reference
itself).
• It allows for flexible and maintainable code by supporting method overriding.
Example code Explanation of the Code:
1. The Animal class defines a method makeSound(), which is
overridden by the Dog and Cat classes.
[Link] reference variable myAnimal is of type Animal, but it holds
objects of Dog and Cat at different times.
[Link] makeSound() is called, Java determines the correct
method implementation at runtime, based on the actual object
type.
Why it is called Dynamic?
Because the JVM decides which method to call while the program is
running, based on the object, not the reference.
Why Use Dynamic Method Dispatch?
• Achieves Runtime Polymorphism: Allows the program to be more
flexible and scalable.
• Enhances Code Reusability: A superclass reference can be used
for multiple subclass objects.
• Improves Maintainability: Reduces dependencies between
different parts of the code.
Usage Of Final Keyword
The final keyword is used to define a constant and to make
attributes, methods, and classes final i.e., non-changeable.
Methods and classes which are defined as final cannot be
inherited and overridden. The final keyword is a non-access
modifier.
The final keyword can be used with the following topics:
• Variables
• Methods
• Classes
Final Variable
A final variable can be explicitly initialized only once. A reference
variable declared final can never be reassigned to refer to an
different object.
However, the data within the object can be changed. So, the state
of the object can be changed but not the reference.
With variable the final modifier often is used with static to make
the constant a class variable.
Usage Of Final Keyword
Final Method
A final method cannot be overridden by any
subclasses. As mentioned previously, the final
modifier prevents a method from being modified
in a subclass.
The main intention of making a method final
would be that the content of the method should
not be changed by any outsider.
Example of Final Method
You declare methods using the final modifier in
the class declaration, as in the following
example −
Usage Of Final Keyword
Final Class
The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is
marked as final then no class can inherit any feature from the final class.
When to Use final Keyword in Java?
The final keyword can be used with variables, methods,
and classes to make them constant so that their value or
properties cannot be changed. The final keyword can be
used for the following context:
• To define a final variable so that its value should not
be changed.
• To define a final method so that it should not be
overridden.
• To define a final class so that it should not be inherited.
Packages
Java Packages
A package in Java is a mechanism to group related classes, interfaces, and sub-packages into a single unit.
Packages help organize large applications, avoid naming conflicts, provide access protection, and make code
modular and maintainable.
• Avoiding name conflicts (two classes with the same name can exist in different packages)
• Providing access control using public, protected, and default access
• Reusability: packaged code can be imported and used anywhere
• Encouraging modular programming
Types of Java Packages
Packages
1. Built-in Packages
Built-in Packages comprise a large number of classes that are part of the Java API. Some of the commonly used built-in
packages are:
• [Link]: Contains language support classes(e.g, classes that define primitive data types, math operations). This
package is automatically imported.
• [Link]: Contains classes for supporting input/output operations.
• [Link]: Contains utility classes that implement data structures such as Linked Lists and Dictionaries, as well as
support for date and time operations.
• [Link]: Contains classes for creating Applets.
• [Link]: Contains classes for implementing the components for graphical user interfaces (like buttons, menus, etc)
Packages
2. User-defined Packages
User-defined Packages are the packages that are defined by the user.
Example:
package [Link];
public class Helper {
public static void show() {
[Link]("Hello from Helper!");
}
}
To use it in another class:
import [Link];
public class Test
{
public static void main(String[] args) {
[Link]();
}}
Packages
In Java, packages are containers for organizing related classes, interfaces, etc., preventing naming conflicts and aiding
modularity; access protection controls visibility using public, protected, private, and default (package-private) specifiers;
and importing brings classes from other packages into your current code using the import keyword, enabling reuse and
structure.
1. Definition of Packages
• What they are: A mechanism to group logically related Java types (classes, interfaces, enums, annotations) into a
single unit, like folders in a file system.
• Purpose:
⚬ Organization: Helps structure large applications.
⚬ Namespace Management: Prevents naming conflicts (e.g., two Date classes can exist in different packages).
⚬ Reusability: Makes code easier to share and reuse.
2. Access Protection
• Packages work with access modifiers to control visibility:
⚬ public: Accessible from any class, anywhere.
⚬ protected: Accessible within the same package and by subclasses in other packages.
⚬ private: Accessible only within the defining class.
⚬ default (package-private): Accessible only within the same package.
• How it works: Packages provide an extra layer of encapsulation, hiding classes or members not meant for external use.
Packages
1. Importing Packages
• Purpose: To use classes from other packages without writing their fully qualified names every time.
• Methods:
⚬ import package_name.ClassName; : Imports a specific class.
⚬ import package_name.*; : Imports all public classes from the package.
⚬ Fully Qualified Name : package_name.ClassName myObj = new package_name.ClassName(); (used without
import).
Interface
⚬ An interface defines a contract (methods/constants) without implementation; a class implements it, providing
method bodies (or becomes abstract). Interfaces can extend other interfaces, inheriting their members and
adding their own, allowing for method-set combinations before a class implements the final interface. This
mechanism achieves abstraction and a form of multiple inheritance, specifying "what to do" (interface) rather
than "how to do it" (class implementation).
Interface
Definition of Interface
What is an Interface?
An interface in Java is a collection of abstract methods that
specifies what a class must do, not how it does it. It is declared
using the interface keyword.
interface Animal {
void sound(); // abstract method
}
Implementation of Interface
How is an Interface Implemented?
A class uses the implements keyword to implement an interface and
must provide method bodies.
Interface
Extending Interfaces
Can an Interface extend another Interface?
Yes.
An interface can extend one or more interfaces using the
extends keyword.
Points to Remember
• Interface methods are public and abstract by default
• Interface variables are public, static, and final
• Interface cannot create objects
• A class can implement multiple interfaces
• Interface supports multiple inheritance
• Interface → A blueprint of a class containing abstract
methods
• Implementation → Providing method body using implements
• Extending interface → One interface inheriting another
interface
Exception
Java Exceptions
As we know different types of errors can occur while running a program - such as coding mistakes, invalid input, or
unexpected situations.
When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will
throw an exception (throw an error).
Exception Handling (try and catch)
Exception handling lets you catch and handle errors during runtime - so your program doesn't crash.
It uses different keywords:
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
The try and catch keywords come in pairs:
Syntax :
try
{
// Block of code to try
}catch(Exception e)
{
// Block of code to handle errors
}
Exception
If an error occurs, we can use try...catch to catch the error and execute some code to handle it:
Exception
Finally
The finally statement lets you execute code, after try...catch, regardless of the result:
Exception
The throw keyword
The throw statement allows you to create a custom error.
The throw statement is used together with an exception type. There are many exception types available in Java:
• ArithmeticException,
• FileNotFoundException,
• ArrayIndexOutOfBoundsException,
• SecurityException, and etc:
Built in Exception
Built in Exception
Built in Exception
Creating Own Exceptions in Java
• The Java programming language allow us to create our own exception classes which are basically subclasses
built-in class Exception.
• To create our own exception class simply create a class as a subclass of built-in Exception class.
• We may create constructor in the user-defined exception class and pass a string to Exception class constructor
using super(). We can use getMessage() method to access the string.
• Let's look at the following Java code that illustrates the creation of user-defined exception.