UNIT –II
1. INHERITANCE
1.1 Basic Concepts of Inheritance
Inheritance is one of the most important concepts in Object-Oriented Programming
(OOP). It allows a new class to acquire the properties and behavior of an existing
class. The main purpose of inheritance is code reusability. Instead of writing the
same code again, we can extend an existing class and use its data members and
methods.
The class that gives its properties is called the superclass or base class.
The class that inherits from another class is called the subclass or derived class.
Benefits of inheritance:
Code reusability
Reduces redundancy
Supports hierarchical classification
Encourages method overriding
Enables runtime polymorphism
Example:
class Animal {
void eat() {
[Link]("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
[Link]("Dog is barking");
}
}
1.2 Types of Inheritance (Refer in unit -1)
1.3 Member Access Rules in Inheritance
Java provides access modifiers to control access levels:
How member access rules work
Member In a derived class (via Accessibility in derived
Type public inheritance) class (and outside)
Public Remains public From derived class: Yes
From outside: Yes
Protected Remains protected From derived class: Yes
From outside: No
Private Not inherited From derived class: No
From outside: No
Key points:
Private members are never inherited: A derived class cannot directly access the
private members of its base class. However, it can use any public or protected
methods that the base class provides to indirectly access its private data.
Protected members are accessible to derived classes: Protected members of a
base class are accessible to its derived classes and any further derived classes, but
they are not accessible from outside the class hierarchy.
Public members are accessible from anywhere: Public members of a base class
can be accessed from the derived class and from anywhere else in the program.
Inheritance type changes accessibility: The type of inheritance (e.g., public,
protected, private) determines how the base class's public and protected members
are inherited. For example, with public inheritance, the access levels are preserved,
while private inheritance makes all inherited members private to the derived class.
1.4 Usage of this Keyword
this refers to the current class object.
Uses:
To refer current class instance variable
To call current class methods
To call current class constructor using this()
To return current class object
Example:
class Student {
int id;
String name;
Student(int id, String name) {
[Link] = id;
[Link] = name;
}
}
1.5 Usage of super Keyword
super refers to the parent class object.
Uses:
Access parent class variables
Call parent class methods
Call parent class constructor using super()
Example:
class A {
A() {
[Link]("Parent Constructor");
}
}
class B extends A {
B() {
super();
[Link]("Child Constructor");
}
}
1.6 Method Overloading
Definition:
Method overloading is a feature in Java where two or more methods in the same
class have the same name but different parameter lists (different type, number,
or order of parameters). It allows a class to perform a similar operation in multiple
ways.
Key Points:
Occurs within a single class.
Method name must be the same.
Parameter lists must be different (number or type).
Return type can be same or different, but return type alone cannot
distinguish overloaded methods.
Helps to increase readability and reusability.
Rules for Method Overloading
1. Methods must have the same name.
2. Methods must have different parameter lists (type, number, or sequence).
3. Methods can have different return types.
4. Methods can have different access modifiers (public, private, protected).
5. Methods cannot be overloaded by changing only the return type.
Example
class Printer {
void print(String s) {
[Link](s);
}
void print(int i) {
[Link](i);
}
void print(double d) {
[Link](d);
}
}
public class Test {
public static void main(String[] args) {
Printer p = new Printer();
[Link]("Hello");
[Link](123);
[Link](45.67);
}
}
1.7 Method Overriding
Definition:
Method overriding occurs when a subclass provides its own implementation of a
method that is already defined in its superclass.
It is used to modify or customize the behavior of inherited methods.
Key Points about Method Overriding:
1. The method name in the subclass must be the same as in the superclass.
2. The parameter list must be exactly the same (number, type, order).
3. The return type must be the same (or compatible in case of covariant return
types).
4. Access modifier in subclass cannot be more restrictive than the superclass
method.
5. Only inherited methods can be overridden.
6. Constructors cannot be overridden.
7. Method overriding is used to achieve runtime polymorphism.
Example:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
[Link]();
}
}
1.8 Abstract Classes
Definition
An abstract class in Java is a class that cannot be instantiated and may contain
both abstract methods (without body) and non-abstract methods (with body).
It is declared using the abstract keyword.
abstract class Shape {
abstract void draw();
}
Key Features of Abstract Classes
An abstract class cannot create objects.
It can contain constructors, which run when a subclass object is created.
It may contain zero or more abstract methods.
A class becomes abstract compulsorily if at least one method is abstract.
Abstract methods cannot be final, because final methods cannot be
overridden.
Abstract classes can have final methods, static methods, variables, and
normal methods.
They support partial abstraction (0–100%).
A subclass must provide implementation for all abstract methods.
If it doesn’t, the subclass must also be declared abstract.
1: Abstract Class with Abstract Method
abstract class Sunstar {
abstract void printInfo();
}
class Employee extends Sunstar {
void printInfo() {
[Link]("avinash");
[Link](21);
[Link](222.2F);
}
}
public class Base {
public static void main(String[] args) {
Sunstar s = new Employee();
[Link]();
}
}
Output
avinash
21
222.2
2: Abstract Class with Constructor & Normal Methods
abstract class Subject {
Subject() {
[Link]("Learning Subject");
}
abstract void syllabus();
void Learn() {
[Link]("Preparing Right Now!");
}
}
class IT extends Subject {
void syllabus() {
[Link]("C , Java , C++");
}
}
public class GFG {
public static void main(String[] args) {
Subject x = new IT();
[Link]();
[Link]();
}
}
Output
Learning Subject
C , Java , C++
Preparing Right Now!
Properties of Abstract Classes
1. Cannot be Instantiated
o An abstract class cannot create objects directly.
o Example: Animal a = new Animal(); // Not allowed.
2. Can Contain Abstract Methods
o Abstract classes may have abstract methods (methods without a body).
o These methods must be implemented by child classes.
3. Can Contain Concrete (Normal) Methods
o Abstract classes can also have normal methods with a body.
o This allows sharing common functionality among subclasses.
4. Can Have Constructors
o Abstract classes can define constructors, which will run when a subclass
object is created.
5. Can Have Variables and Constants
o Abstract classes can contain instance variables, static variables, and
final variables.
o Interfaces cannot have instance variables
abstract class Animal {
abstract void sound();
// normal method
void sleep() {
[Link]("Sleeping...");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
class Main {
public static void main(String[] args) {
Animal a = new Dog(); reference
[Link]();
[Link]();
}
}
1.9 Dynamic methods dispatch
Dynamic Method Dispatch, also known as Runtime Polymorphism, is a
mechanism in Java where the method to be executed is determined at runtime rather
than at compile time. This mechanism is crucial for achieving method overriding in
object-oriented programming.
Key Concepts:
Method Overriding:
A subclass provides a specific implementation for a method that is already
defined in its superclass.
Upcasting:
A superclass reference variable can refer to an object of a subclass. This is a
fundamental aspect of dynamic method dispatch.
Runtime Resolution:
When an overridden method is invoked through a superclass reference, Java
determines which version of the method (from the superclass or subclass) to
execute based on the actual type of the object being referred to at the time of
the call, not the type of the reference variable
Example
class Animal {
public void move() {
[Link]("Animals can move");
}
}
class Dog extends Animal {
public void move() {
[Link]("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal();
Animal b = new Dog();
[Link]();
[Link]();
}
}
Output
Animals can move
Dogs can walk and run
1.10 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:
1. Variables
2. Methods
3. Classes
1. final Variable
A final variable’s value cannot be changed once assigned.
It becomes a constant.
Must be initialized at the time of declaration or inside a constructor.
Example:
final int x = 10;
// x = 20;
2. final Method
A final method cannot be overridden by a subclass.
Used to prevent modification of important methods.
Example:
class A {
final void show() {
[Link]("Final method in A");
}
}
class B extends A {
// void show() {}
}
3. final Class
A final class cannot be extended (no subclass possible).
Used to prevent inheritance and modification of class behavior.
Example:
final class A {
void display() {
[Link]("Inside A");
}
}
Packages
1. Definition of Packages
A package in Java is a way of grouping related classes, interfaces, and sub-
packages together.
It helps in organizing Java programs and avoids name conflicts.
Packages work like folders inside a project.
Java has two types of packages:
1. Built-in packages ([Link], [Link], [Link], etc.)
2. User-defined packages
Example:
package mypack;
class A {
void display() {
[Link]("Inside package");
}
}
2. Access Protection in Packages
Access protection decides which classes and members can be accessed outside or
inside the package.
Java uses four access modifiers:
Explanation:
public → accessible everywhere
protected → accessible in same package + subclasses
default → accessible only in same package
private → accessible inside class only
3. Importing Packages
To use another package’s classes, we use the import keyword.
a) Import a specific class
import [Link];
b) Import all classes from a package
import [Link].*;
c) Import user-defined package
mypack/[Link]
package mypack;
public class A {
public void show() {
[Link]("Hello from package");
}
}
[Link]
import mypack.A;
class Main {
public static void main(String[] args) {
A obj = new A();
[Link]();
}
}
Interfaces
1. Definition of Interface in Java
An interface in Java is a fully abstract structure used to specify a set of
methods that a class must implement.
It is declared using the keyword interface.
Interfaces contain abstract methods (before Java 8) and default/static
methods (after Java 8).
A class uses implements to use an interface.
Interfaces support multiple inheritance in Java.
Example:
interface Animal {
void sound();
}
2. Implementing an Interface
A class must provide the method definitions of all abstract methods inside the
interface.
Example:
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
[Link]("Dog barks");
}
}
class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}
Output:
Dog barks
Key Rules During Implementation:
Use implements keyword.
Must override all methods of the interface.
If not implemented, the class must be declared abstract.
3. Extending Interfaces
an interface can extend another interface. When an interface wants to extend
another interface, it uses the keyword extends. The interface that extends another
interface has its own members and all the members defined in its parent interface
too. The class which implements a child interface needs to provide code for the
methods defined in both child and parent interfaces, otherwise, it needs to be
defined as abstract class.
An interface can extend another interface.
An interface can not extend multiple interfaces.
An interface can implement neither an interface nor a class.
The class that implements child interface needs to provide code for all the
methods defined in both child and parent interfaces.
interface A {
void show();
}
interface B extends A {
void display();
}
class Test implements B {
public void show() {
[Link]("Showing A");
}
public void display() {
[Link]("Displaying B");
}
}
class Main {
public static void main(String[] args) {
Test t = new Test();
[Link]();
[Link]();
}
}
Output:
Showing A
Displaying B
Exception Handling
Exception Handling is a mechanism to manage runtime errors so that the normal
flow of the program is not interrupted.
Java uses a structured way to detect, handle, and recover from errors.
1. try Block
The try block contains code that may cause an exception.
It is always followed by catch or finally.
Example:
try {
int x = 10 / 0;
}
2. catch Block
The catch block handles the exception thrown by the try block.
You can have multiple catch blocks.
Example:
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
}
3. finally Block
The finally block always executes, whether exception occurs or not.
Used for cleanup operations (closing files, releasing resources).
Example:
try {
int a = 5;
} catch(Exception e) {
[Link]("Error");
} finally {
[Link]("Always runs");
}
4. throw Keyword
Used to explicitly throw an exception.
Mainly used for custom validation.
Example:
throw new ArithmeticException("Invalid Operation");
5. throws Keyword
Added in method signature to indicate that the method may throw an
exception.
Used to forward exception handling responsibility to the caller.
Example:
void myMethod() throws IOException {
}
Built in exception
The Java programming language has several built-in exception class that
support exception handling. Every exception class is suitable to explain certain error
situations at run time.
All the built-in exception classes in Java were defined a package [Link].
Common Built-in Exceptions in Java
Java defines several other types of exceptions that relate to its various class libraries.
Following is the list of Java Unchecked and Checked RuntimeException.
[Link]. Exception & Description
ArithmeticException
1
Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException
2
Array index is out-of-bounds.
ArrayStoreException
3
Assignment to an array element of an incompatible type.
ClassCastException
4
Invalid cast.
IllegalArgumentException
5
Illegal argument used to invoke a method.
IllegalMonitorStateException
6
Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException
7
Environment or application is in incorrect state.
IllegalThreadStateException
8
Requested operation not compatible with the current thread state.
IndexOutOfBoundsException
9
Some type of index is out-of-bounds.
NegativeArraySizeException
10
Array created with a negative size.
NullPointerException
11
Invalid use of a null reference.
NumberFormatException
12
Invalid conversion of a string to a numeric format.
13 SecurityException
Attempt to violate security.
StringIndexOutOfBounds
14
Attempt to index outside the bounds of a string.
UnsupportedOperationException
15
An unsupported operation was encountered.
Creating Own Exceptions Classes
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.
Example program
class MyException extends Exception {
MyException(String msg) {
super(msg);
}
}
public class Test {
public static void main(String[] args) {
try {
int age = 15;
if(age < 18)
throw new MyException("Not Eligible!");
[Link]("Eligible");
}
catch(MyException e) {
[Link]([Link]());
}
}
}