Inheritance, Abstract Class,
Interface, Package and
Exceptions
Amar Jukuntla,
Assistant Professor, ACSE,
VFSTR University
Index
• Introduction to inheritance
• Method overriding
• Usage of final keyword
• Abstract Classes
• Interfaces
• Access Control
• Packages
• Exception handling
• References
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Introduction to Inheritance
• The inheritance relationship
enables a derived class to
inherit features from its base
class.
• A derived class can add new
features of its own.
• Therefore, rather than creating
completely new classes from
scratch, we can take advantage
of inheritance and reduce
software complexity.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Inheritance
(Super/ Parent/Base )
A
❖ In java extends is the keyword used to inherit the other class.
Syntax:
class subclass-name extends superclass-name
{
// body of class
}
(Sub/ Child/ Derived)
B
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Example
• Class: A class is a group of objects which have common properties. It
is a template or blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class that inherits the other
class. It is also called a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a
subclass inherits the features. It is also called a base class or a parent
class.
• Reusability: As the name specifies, reusability is a mechanism that
facilitates you to reuse the fields and methods of the existing class
when you create a new class. You can use the same fields and methods
already defined in the previous class.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Types of Inheritance
• Single Inheritance
• Multiple Inheritance
• Hierarchical Inheritance
• Multilevel Inheritance
• Hybrid Inheritance
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Single Inheritance
• It is the inheritance hierarchy wherein one derived class inherits from
one base class. class A class Demo
{ {
public int x=10; public static void main (String args[])
A Super Class void showA ( ) {
{ B b= new B();
System. out. println (x); b.showA ():
} b.add ():
} }
class B extends A }
{
int y=20;
B Sub Class void add()
{ 10
System.out.println(x+y);
} 30
}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Multilevel Inheritance
• It is the inheritance hierarchy wherein subclass acts as a base class for
other classes. class A class C extends B
{
public int x=10; {
A void showA ( )
Super Class int z =10;
{
System. out. println (x); void showC ()
} {
B }
Super / subClass class B extends A System.out.println(x+y+z);
{ }
int y=10;
void showB() }
C {
Sub Class System.out.println(x+y);
}
}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Multilevel Inheritance
class Demo
{
public static void main(String args[ ])
{
C c= new C (); 10
c.showA (); 20
c.showB ();
30
c.showC ( );
}
}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Multiple Inheritance
• It is the inheritance hierarchy wherein one derived class inherits from
multiple base classes.
Super Class A B Super Class
In JAVA, it does not support multiple inheritance directly;
C but by using interfaces multiple inheritance is possible.
Sub Class
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Hierarchical Inheritance
• It is the inheritance hierarchy wherein multiple derived classes inherit
from one base class.
A
Super Class
B C D
SubClass SubClass SubClass
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Hierarchical Inheritance
class A class C extends A class Demo
{ {
public int x=10; public int x=10; {
void showA ( ) void showC ( ) public static void main(String args[ ])
{ {
System. out. println (x); System. out. println (x); {
} } B b=new B();
} } C c= new C ();
class B extends A class D extends A D d= new D ();
{ { b.showA ();
int y=10; int y=10; c.showA ();
void showB() void showD() d.showA ( );
{ { }
System.out.println(x+y); System.out.println(x+y); 10
}
} } 10
} }
10
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Hybrid Inheritance
• It is the inheritance hierarchy that reflects any legal combination of the
other four types of inheritance
SuperClass
A
B C
SubClass
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Method overriding
• If subclass (child class) has the same method as declared in
the parent class, it is known as method overriding in Java.
• In other words, If a subclass provides the specific implementation of
the method that has been declared by one of its parent class, it is
known as method overriding.
• Method overriding is used for runtime polymorphism
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Example
class Animal { class Dog extends Animal {
// Method in the superclass // Overriding the method in the subclass
public void makeSound() { @Override
System.out.println("The animal makes a sound"); public void makeSound() {
} System.out.println("The dog barks");
} }
}
class Cat extends Animal {
// Overriding the method in the subclass public class Main {
@Override public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create an Animal object
public void makeSound() {
Animal myDog = new Dog(); // Create a Dog object
System.out.println("The cat meows"); Animal myCat = new Cat(); // Create a Cat object
}
} myAnimal.makeSound(); // Calls the method in Animal class
myDog.makeSound(); // Calls the overridden method in Dog class
myCat.makeSound(); // Calls the overridden method in Cat class
}
} The animal makes a sound
The dog barks
Amar Jukuntla | Department of Advanced Computer Science and Engineering The cat meows
Usage of final keyword
• The final keyword in java is used to restrict the user.
• The java final keyword can be used in many context. Final
can be:
• variable
• method
• class
• By using the final keyword, you can create constants,
prevent method overriding, and prohibit class
inheritance, ensuring greater control over the behavior of
your classes and methods.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Usage of final keyword
• A final variable can be assigned only once. Once assigned, its
value cannot be changed.
• Example: final int MAX_SPEED = 90;
• A final method cannot be overridden by subclasses.
• A final class cannot be subclassed.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Example
class A {
final void meth() { final class A {
System.out.println("This is a final method."); // ...
} }
} // The following class is illegal.
class B extends A { class B extends A { // ERROR! Can't subclass A
void meth() { // ERROR! Can't override. // ...
System.out.println("Illegal!"); }
}
}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Usage of super keyword
• Whenever a subclass needs to refer to its
immediate superclass, it can do so by use of the
keyword super.
• super has two general forms.
• The first calls the superclass’ constructor.
• The second is used to access a member of the
superclass that has been hidden by a member of a
subclass.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
First Form of Super
A subclass can call a
constructor defined
by its superclass by super(arg-list);
use of the following
form of super:
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Example
class Box{ class BoxWeight extends Box{
double width; double weight;
double height; BoxWeight(double w,double h,double d,double m)
double depth; {
Box(double w, double h, double d) super(w,h,d);
{ weight=m;
width=w; }
height=h; }
depth=d;
}
}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Second form of super
• The second form of super acts somewhat like this, except that
it always refers to the superclass of the subclass in which it is
used. This usage has the following general form:
super.member
• Here, member can be either a method or an instance variable.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Example
class Box{ class BoxWeight extends Box{
double width; Base Class BoxWeight(double w,double h,double d,double m)
double height; {
double depth; super(w,h,d);
Sub Class
double weight; super.weight=m;
Box(double w, double h, double d) }
{ }
width=w;
height=h;
depth=d;
}
}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Abstract Classes
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Abstract Class
• Abstraction is a process of hiding the implementation
details and showing only functionality to the user.
• A class which is declared with the abstract keyword is
known as an abstract class in Java.
• It can have abstract and non-abstract methods (method with the
body).
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Key Points About Abstract Classes
Cannot be instantiated: You cannot create an object of an abstract class
directly.
Can have abstract methods: These methods do not have a body and
must be implemented by subclasses.
Can have concrete methods: These methods have a body and provide a
default implementation.
Can have fields and constructors: Like regular classes, abstract classes
can have fields and constructors, though constructors are called only through subclass
instantiation.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Parent class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void makeSound();
// Regular method
public void sleep() {
System.out.println("The animal is sleeping");
}
}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Sub
Sub
Class class Dog extends Animal { Class
// Provide implementation for the abstract method
class Cat extends Animal {
@Override
// Provide implementation for the abstract method
public void makeSound() {
@Override
System.out.println("The dog barks");
public void makeSound() {
}
System.out.println("The cat meows");
}
}
public class Main { }
public static void main(String[] args) {
Animal myDog = new Dog(); // Create a Dog object
Animal myCat = new Cat(); // Create a Cat object
Main myDog.makeSound(); // Calls the overridden makeSound() method in Dog
Class myDog.sleep(); // Calls the inherited sleep() method from Animal Output
The dog barks
myCat.makeSound(); // Calls the overridden makeSound() method in Cat
The animal is sleeping
myCat.sleep(); // Calls the inherited sleep() method from Animal
The cat meows
}
The animal is sleeping
}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Interfaces
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Interface
• An interface in java is a mechanism to achieve abstraction. Like
a class, an interface can have methods and variables, but the methods
declared in interface are by default abstract (only method signature, no
body).
• It is used to achieve abstraction and multiple
inheritance in Java.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Interface
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Relation between Class and Interface
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Multiple Inheritance in Java
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Example
interface Animal { class Dog implements Animal {
// Constant // Provide implementation for the abstract
int MAX_AGE = 20; method
// Abstract method @Override
void makeSound(); public void makeSound() {
System.out.println("The dog barks");
// Default method }
default void sleep() { }
System.out.println("The animal is sleeping");
} class Cat implements Animal {
// Static method // Provide implementation for the abstract method
static void describe() { @Override
System.out.println("Animals are living beings that public void makeSound() {
move and consume organic material."); System.out.println("The cat meows");
} }
} }
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Main Class
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
Cat myCat = new Cat();
// Call methods on the instances Output
myDog.makeSound(); The dog barks
myDog.sleep(); The animal is sleeping
myCat.makeSound(); The cat meows
myCat.sleep(); The animal is sleeping
Animals are living beings that move and consume
// Call static method from the interface organic material.
Animal.describe(); Max age of an animal: 20
// Access the constant from the interface
System.out.println("Max age of an animal: " +
Animal.MAX_AGE);
}
}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Interface
• Some Important Points to remember about Java Interfaces
• Interfaces specify what a class must do and not how. It is the
blueprint of the class.
• If a class implements an interface and does not provide method
bodies for all functions specified in the interface, then class must be
declared abstract.
• By interface, we can support the functionality of multiple
inheritance.
• You cannot instantiate an interface.
• An interface does not contain any constructors.
• All of the methods in an interface are abstract.
• An interface cannot contain instance fields. The only fields that can
appear in an interface must be declared both static and final.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Interface
• An interface is not extended by a class; it is implemented by a
class.
• An interface can extend multiple interfaces.
• An interface can contain any number of methods.
• An interface is written in a file with a .java extension, with the
name of the interface matching the name of the file.
• The byte code of an interface appears in a .class file.
• Interfaces appear in packages, and their corresponding bytecode
file must be in a directory structure that matches the package name.
• We can’t create instance(interface can’t be instantiated) of interface
but we can make reference of it that refers to the Object of its
implementing class.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Packages
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Package
A java package is a group of similar types of classes, interfaces
and sub-packages.
Package in java can be categorized in two form, built-in package
and user-defined package.
There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Advantage of Java Package
Java package is used to categorize the classes and interfaces
so that they can be easily maintained.
Java package provides access protection.
Java package removes naming collision.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Package
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Package Creation
The package keyword is used to create a package in java.
1.//save as Simple.java .
javac -d Simple.java
2.package mypack;
3.public class Simple{
Current Directory
4. public static void main(String args[]){
5. System.out.println("Welcome to package"); Output
6. }
7.} Welcome to package
How to compile java package javac -d directory javafilename
To Run: java mypack.Simple
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Example: Bank
package Bank;
public int withdraw()
public class BankAccount{
{
public int ac, num, total=1000;
total=total-num;
public String name;
return total;
public BankAccount(int a, String b, int c)
}
{
public void display()
ac=a; name=b; num=c; {
} System.out.println("Account Number:"+ac+"\n");
public int deposit() System.out.println("Account Holder
{ Name:"+name+"\n");
total=total+num; System.out.println("Initial Ammount:"+num+"\n");
return total; }
} }
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Example: Bank Compilation
Save the file with BankAccount.java
According to hierarchy a BankAccount.class file should be present in
the subdirectory “Bank” in the present in current directory while
compiling the above file use the following command
javac –d . BankAccount.java
-d option specifies the destination directory where the package hierachy
is to be created.
The above command compiles the above file.java resulting job file is
placed in the subdirectory Bank which is also created by the compiler
in the current directory.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Importing a package in class
import Bank.BankAccount; Compilation
class BankMain{ javac BankMain.java
public static void main(String args[])
java BankMain
{
BankAccount bac=new BankAccount(1,"AMAR",100);
bac.display();
System.out.println("Ammount After Deposit:\t"+bac.deposit()+"\n");
System.out.println("Ammount After Withdraw:\t"+bac.withdraw()+"\n");
System.out.println("Withdrawn Money Again:\t"+bac.withdraw()+"\n");
}
}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Access Control
• There are four types of
Java access modifiers:
• Private
• Default
• Protected
• Public
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Access Control
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Access Control
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Exception Handling
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Exception in Java
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Exception Handling
• Exception handling in Java is a mechanism that allows developers to
manage and respond to runtime errors or exceptional
conditions gracefully without terminating the program
unexpectedly.
• It ensures the smooth execution of the program even when errors
occur.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Exception Handling
• Exception Handling is a mechanism
to handle runtime errors such as
ClassNotFoundException,IOExceptio
n,SQLException,RemoteException,et
c.
• The core advantage of exception
handling is to maintain the normal
flow of the application. An exception
normally disrupts the normal flow of
the application; that is why we need
to handle exceptions.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Java Exception Handling Keywords
• There are 5 keywords used in java exception
handling.
• try
• catch
• finally
• throw
• throws
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Java Exception Handling Keywords
• try: Defines a block of code to monitor for exceptions.
• catch: Defines a block of code to handle specific exceptions.
• finally: Defines a block of code that will execute regardless of
whether an exception occurred or not.
• throw: Used to explicitly throw an exception.
• throws: Declares exceptions that a method can throw.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Exception hierarchy
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Java Exception Hierarchy
• Superclass Throwable
• Subclass Exception
• Exceptional situations
• Should be caught by program
• Subclass Error
• Typically, not caught by program
• Checked exceptions
• Catch or declare
• Unchecked exceptions
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Types of Exception
• There are mainly two types of exceptions: checked and
unchecked where error is considered as unchecked
exception. The sun microsystem says there are three
types of exceptions:
• Checked Exception
• Unchecked Exception
• Error
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Checked Exceptions
• These are exceptions that are checked at compile-time. The
Java compiler mandates that these exceptions must either be
caught using a try-catch block or declared in the method
signature using the throws keyword.
• Example:
• IOException: Issues during file operations.
• SQLException: Problems with database operations.
• FileNotFoundException: File not found in the specified location.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Unchecked Exceptions
• These are exceptions that are not checked at compile-time.
The programmer can choose whether or not to handle them
explicitly. If not handled, they cause the program to terminate
at runtime.
• Example:
• ArithmeticException: Division by zero.
• NullPointerException: Attempting to access methods or fields on
a null object reference.
• ArrayIndexOutOfBoundsException: Accessing an invalid array
index.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Error
• Errors are serious issues that occur at the system level, and
they are not meant to be handled by the application. These
belong to the Error class and are not checked at compile-time.
• Example:
• OutOfMemoryError: JVM runs out of memory.
• StackOverflowError: Infinite recursion causes the stack to
overflow.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Java try block
• The try block contains the code that might throw an exception. If an
exception occurs, the control is transferred to the catch block.
• Java try block must be followed by either catch or finally block.
Syntax of java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw exception
}finally{}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Exception Handler
Exception
"thrown" here
Thrown exception matched against first
set of exception handlers
Exception
handler
If it fails to match, it is matched against
next set of handlers, etc.
Exception
handler
If exception matches none of handlers,
program is abandoned
Amar Jukuntla | Department of Advanced Computer Science and Engineering
try block
• The try block contains the code that might throw an exception. If an
exception occurs, the control is transferred to the catch block.
try {
// Code that might throw an exception
int data = 50 / 0;
// This will throw ArithmeticException
}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
catch Block
• The catch block handles the exception. It must follow the try block.
You can have multiple catch blocks to handle different types of
exceptions.
catch (ArithmeticException e) {
// Code to handle the ArithmeticException
System.out.println("Cannot divide by zero");
}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
finally Block
• The finally block contains code that is always executed, regardless of
whether an exception is thrown or not. It's often used
to close resources like files or database connections.
finally {
// Code that will execute regardless of an exception
System.out.println("Finally block is always executed");
}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
throw Keyword
• The throw keyword is used to explicitly throw an exception. You can
throw both checked and unchecked exceptions.
if (age < 18) {
throw new ArithmeticException("Not valid age");
}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
throws Keyword
• The throws keyword is used in method signatures to indicate that a
method might throw one or more exceptions.
public void method() throws IOException, SQLException
{
// Method code
}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Basis of throw throws
Differences
Definition Java throw keyword is used throw an exception Java throws keyword is used in the method
explicitly in the code, inside the function or the signature to declare an exception which might be
block of code. thrown by the function while the execution of the
code.
Usage Type of exception Using throw keyword, we can Using throws keyword, we can declare both
only propagate unchecked exception i.e., the checked and unchecked exceptions. However, the
checked exception cannot be propagated using throws keyword can be used to propagate checked
throw only. exceptions only.
Syntax The throw keyword is followed by an instance of The throws keyword is followed by class names of
Exception to be thrown. Exceptions to be thrown.
Declaration throw is used within the method. throws is used with the method signature.
Internal implementation We are allowed to throw only one exception at a We can declare multiple exceptions using throws
time i.e. we cannot throw multiple exceptions. keyword that can be thrown by the method. For
example, main() throws IOException,
SQLException.
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Example
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int[] arr = new int[5]; arr[5] = 30 / 0;
// This will throw ArrayIndexOutOfBoundsException and ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bounds Exception: " + e.getMessage());
} catch (Exception e) {
System.out.println("Parent Exception: " + e.getMessage());
} finally {
System.out.println("Finally block is always executed");
}
}
}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
Custom Exception Example
class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
try {
throw new MyCustomException("This is a custom exception");
} catch (MyCustomException e) {
System.out.println("Caught custom exception: " + e.getMessage());
}
}
}
Amar Jukuntla | Department of Advanced Computer Science and Engineering
References
• https://www.javatpoint.com/method-overriding-in-java
• https://www.javatpoint.com/final-keyword
• https://www.javatpoint.com/abstract-class-in-java
• https://simplesnippets.tech/java-interfaces-explained-with-program-
examples/#google_vignette
• https://www.w3schools.com/java/java_try_catch.asp
Amar Jukuntla | Department of Advanced Computer Science and Engineering
THANK
YOU