0% found this document useful (0 votes)
6 views

Java_Unit 2

The document discusses inheritance in Java, a key concept in Object-Oriented Programming that allows one class to inherit fields and methods from another, promoting code reusability and abstraction. It covers various types of inheritance, including single, multilevel, hierarchical, multiple (through interfaces), and hybrid inheritance, along with examples for each type. Additionally, it explains Java access modifiers, the use of 'super' and 'this' keywords, and concludes with a brief mention of method overloading.

Uploaded by

Magesh Bala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java_Unit 2

The document discusses inheritance in Java, a key concept in Object-Oriented Programming that allows one class to inherit fields and methods from another, promoting code reusability and abstraction. It covers various types of inheritance, including single, multilevel, hierarchical, multiple (through interfaces), and hybrid inheritance, along with examples for each type. Additionally, it explains Java access modifiers, the use of 'super' and 'this' keywords, and concludes with a brief mention of method overloading.

Uploaded by

Magesh Bala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

UNIT – 2

Inheritance in Java
Java, Inheritance is an important pillar of OOP (Object-Oriented Programming). It is the mechanism in Java
by which one class is allowed to inherit the features (fields and methods) of another class. In Java,
Inheritance means creating new classes based on existing ones. A class that inherits from another class can
reuse the methods and fields of that class. In addition, you can add new fields and methods to your current
class as well.

Why Do We Need Java Inheritance?

 Code Reusability: The code written in the Superclass is common to all subclasses. Child classes can
directly use the parent class code.
 Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the ways
by which Java achieves Run Time Polymorphism.
 Abstraction: The concept of abstract where we do not have to provide all details, is achieved
through inheritance. Abstraction only shows the functionality to the user.
Important Terminologies Used in Java Inheritance
 Class: Class is a set of objects which shares common characteristics/ behavior and common
properties/ attributes. Class is not a real-world entity. It is just a template or blueprint or prototype
from which objects are created.
 Super Class/Parent Class: The class whose features are inherited is known as a superclass(or a base
class or a parent class).
 Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a derived
class, extended class, or child class). The subclass can add its own fields and methods in addition to
the superclass fields and methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new
class and there is already a class that includes some of the code that we want, we can derive our
new class from the existing class. By doing this, we are reusing the fields and methods of the
existing class.

How to Use Inheritance in Java?


The extends keyword is used for inheritance in Java. Using the extends keyword indicates you are derived
from an existing class. In other words, “extends” refers to increased functionality.
Syntax :
Class DerivedClass extends BaseClass
{
//methodsandfields
}

Example
In the below example of inheritance, class Employee is a base class, class Engineer is a derived class that
extends the Employee class and class Test is a driver class to run the program.
// Java Program to illustrate Inheritance (concise)
import java.io.*;

// Base or Super Class


class Employee {
int salary = 60000;
}

// Inherited or Sub Class


class Engineer extends Employee {
int benefits = 10000;
}

// Driver Class
class Gfg {
public static void main(String args[])
{
Engineer E1 = new Engineer();
System.out.println("Salary : " + E1.salary + "\nBenefits : " + E1.benefits);
}
}
Output
Salary : 60000
Benefits : 10000

Types of Inheritance in Java


1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid 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. In the below figure, ‘A’ is a parent class and ‘B’ is a child class. The class ‘B’
inherits all the properties of the class ‘A’.

Example
// Java program to illustrate the
// concept of single inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

// Parent class
class One {
public void print_geek()
{
System.out.println("Geeks");
}
}

class Two extends One {


public void print_for() { System.out.println("for"); }
}

// Driver class
public class Main {
// Main function
public static void main(String[] args)
{
Two g = new Two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output
Geeks
for
Geeks

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. In the below
image, class A serves as a base class for the derived class B, which in turn serves as
a base class for the derived class C. In Java, a class cannot directly access
the grandparent’s members.

Example
// Importing required libraries
import java.io.*;
import java.lang.*;
import java.util.*;

// Parent class One


class One {
// Method to print "Geeks"
public void print_geek() {
System.out.println("Geeks");
}
}

// Child class Two inherits from class One


class Two extends One {
// Method to print "for"
public void print_for() {
System.out.println("for");
}
}

// Child class Three inherits from class Two


class Three extends Two {
// Method to print "Geeks"
public void print_lastgeek() {
System.out.println("Geeks");
}
}

// Driver class
public class Main {
public static void main(String[] args) {
// Creating an object of class Three
Three g = new Three();
// Calling method from class One
g.print_geek();

// Calling method from class Two


g.print_for();

// Calling method from class Three


g.print_lastgeek();
}
}
Output
Geeks
for
Geeks
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for
more than one subclass. In the below image, class A serves as a base class for
the derived classes B, C, and D.

Example
// Java program to illustrate the
// concept of Hierarchical inheritance

class A {
public void print_A() { System.out.println("Class A"); }
}

class B extends A {
public void print_B() { System.out.println("Class B"); }
}

class C extends A {
public void print_C() { System.out.println("Class C"); }
}

class D extends A {
public void print_D() { System.out.println("Class D"); }
}

// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();

C obj_C = new C();


obj_C.print_A();
obj_C.print_C();

D obj_D = new D();


obj_D.print_A();
obj_D.print_D();
}
}
Output
Class A
Class B
Class A
Class C
Class A
Class D
4. Multiple Inheritance (Through Interfaces)
In Multiple inheritances, one class can have more than one superclass and
inherit features from all parent classes. Please note that Java
does not support multiple inheritances with classes. In Java, we can
achieve multiple inheritances only through Interfaces. In the image
below, Class C is derived from interfaces A and B.

Example
// Java program to illustrate the
// concept of Multiple inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

interface One {
public void print_geek();
}

interface Two {
public void print_for();
}

interface Three extends One, Two {


public void print_geek();
}
class Child implements Three {
@Override public void print_geek()
{
System.out.println("Geeks");
}

public void print_for() { System.out.println("for"); }


}

// Drived class
public class Main {
public static void main(String[] args)
{
Child c = new Child();
c.print_geek();
c.print_for();
c.print_geek();
}
}
Output
Geeks
for
Geeks
5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t
support multiple inheritances with classes, hybrid inheritance involving multiple
inheritance is also not possible with classes. In Java, we can achieve hybrid
inheritance only through Interfaces if we want to involve multiple inheritance to
implement Hybrid inheritance.
However, it is important to note that Hybrid inheritance does not necessarily require
the use of Multiple Inheritance exclusively. It can be achieved through a combination of Multilevel
Inheritance and Hierarchical Inheritance with classes, Hierarchical and Single Inheritance with classes.
Therefore, it is indeed possible to implement Hybrid inheritance using classes alone, without relying on
multiple inheritance type.

Java - Access Modifiers


Java access modifiers are used to specify the scope of the variables, data members, methods, classes,
or constructors. These help to restrict and secure the access (or, level of access) of the data.
There are four different types of access modifiers in Java, we have listed them as follows:
 Default (No keyword required)
 Private
 Protected
 Public

1. Default Access Modifier


If you don't use any modifier, it is treated as default by default. The default modifier is accessible only

within package. It cannot be accessed from outside the package. It provides more accessibility than

private. But, it is more restrictive than protected, and public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class from outside
its package, since A class is not public, so it cannot be accessed from outside the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.

2. Private Access Modifier

Methods, variables, and constructors that are declared private can only be accessed within the declared
class itself.

Private access modifier is the most restrictive access level. Class and interfaces cannot be private.

Variables that are declared private can be accessed outside the class, if public getter methods are present in
the class.

Using the private modifier is the main way that an object encapsulates itself and hides data from the
outside world.

In this example, we will create two classes A and B within the same package p1. We will declare a method
in class A as private and try to access this method from class B and see the result.

// error while using class from different package with


// private access modifier
package p1;

// Class A
class A {
private void display() {
System.out.println("GeeksforGeeks");
}
}

// Class B
class B {
public static void main(String args[]) {
A obj = new A();

// Trying to access private method


// of another class
obj.display();
}
}
Explanation: The above code will show a compile-time error when trying to access a private method from
class B, even within the same package.

3. Protected Access Modifier

The protected access modifier is specified using the keyword protected. The methods or data members
declared as protected are accessible within the same package or subclasses in different packages.
In this example, we will create two packages, p1 and p2. Class A in p1 has a protected method display. Class
B in p2 extends A and accesses the protected method through inheritance by creating an object of class B.

// protected modifier

package p2;

// importing all classes


// in package p1
import p1.*;

// Class B is subclass of A
class B extends A {
public static void main(String args[]) {
B obj = new B();
obj.display();
}
}
Explanation: The above example demonstrates that a protected method is accessible in a subclass from a
different package using inheritance.

4. Public Access Modifier


The public access modifier is specified using the keyword public.
 The public access modifier has the widest scope among all other access modifiers.
 Classes, methods, or data members that are declared as public are accessible from everywhere in
the program. There is no restriction on the scope of public data members.

Example shows that a public method is accessible across packages.


// public access modifier
package p2;

import p1.*;

class B {
public static void main(String args[]) {

A obj = new A();


obj.display();
}
}
Comparison Table of Access Modifiers in Java

Algorithm to Use Access Modifier in Java


Here’s a basic algorithm for using access modifiers in Java:
 Define a class: Create a class to represent the object you want to manage.
 Define instance variables: Inside the class, define variables for the data you want to manage.
 Set an access modifier:
o Use private for variables only accessible within the class.
o Use protected for variables accessible within the class and its subclasses.
o Use public for variables accessible from anywhere.
 Use getter and setter methods: To access or modify variables, use getter (accessor) and setter
(mutator) methods, even for public variables, to maintain encapsulation.
super and this keywords in Java
In java, super keyword is used to access methods of the parent class while this is used to access methods of
the current class.
this keyword
It is a reserved keyword in java i.e., we can’t use it as an identifier. It is used to refer current class’s instance
as well as static members. It can be used in various contexts as given below:
 to refer instance variable of current class
 to invoke or initiate current class constructor
 can be passed as an argument in the method call
 can be passed as argument in the constructor call
 can be used to return the current class instance
Example
// Program to illustrate this keyword
// is used to refer current class
class RR {
// instance variable
int a = 10;

// static variable
static int b = 20;
void GFG()
{
// referring current class(i.e, class RR)
// instance variable(i.e, a)
this.a = 100;
System.out.println(a);
// referring current class(i.e, class RR)
// static variable(i.e, b)
this.b = 600;
System.out.println(b);
}
public static void main(String[] args)
{
// Uncomment this and see here you get
// Compile Time Error since cannot use
// 'this' in static context.
// this.a = 700;
new RR().GFG();
}
}
Output
100
600
super keyword
1. super is a reserved keyword in java i.e, we can’t use it as an identifier.
2. super is used to refer super-class’s instance as well as static members.
3. super is also used to invoke super-class’s method or constructor.
4. super keyword in java programming language refers to the superclass of the class where the super
keyword is currently being used.
5. The most common use of super keyword is that it eliminates the confusion between the super
classes and subclasses that have methods with same name.
super can be used in various contexts as given below:
 it can be used to refer immediate parent class instance variable
 it can be used to refer immediate parent class method
 it can be used to refer immediate parent class constructor.
Example
// Program to illustrate super keyword
// refers super-class instance

class Parent {
// instance variable
int a = 10;

// static variable
static int b = 20;
}

class Base extends Parent {


void rr()
{
// referring parent class(i.e, class Parent)
// instance variable(i.e, a)
System.out.println(super.a);

// referring parent class(i.e, class Parent)


// static variable(i.e, b)
System.out.println(super.b);
}
public static void main(String[] args)
{
// Uncomment this and see here you get
// Compile Time Error since cannot use 'super'
// in static context.
// super.a = 700;
new Base().rr();
}
}
Output
10
20

Difference Between this and super keyword

this Super
The current instance of the class is represented The current instance of the parent class is
by this keyword. represented by the super keyword.

In order to call the default constructor of the In order to call the default constructor of the
current class, we can use this keyword. parent class, we can use the super keyword.

It can be referred to from a static context. It It can be referred to from a static context. It
means it can be invoked from the static context. means it can be invoked from the static context.

We can use it to access only the current class We can use it to access the data members and
data members and member functions. member functions of the parent class.

Java Method Overloading


In Java, two or more methods may have the same name if they differ in parameters (different number of
parameters, different types of parameters, or both). These methods are called overloaded methods and this
feature is called method overloading. For example:
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
Here, the func() method is overloaded. These methods have the same name but accept different
arguments.

Overloading by changing the number of parameters


class MethodOverloading {
private static void display(int a){
System.out.println("Arguments: " + a);
}
private static void display(int a, int b){
System.out.println("Arguments: " + a + " and " + b);
}
public static void main(String[] args) {
display(1);
display(1, 4);
}
}

Output:
Arguments: 1
Arguments: 1 and 4
2. Changing Data Types of the Arguments
In many cases, methods can be considered Overloaded if they have the same name but have different
parameter types, methods are considered to be overloaded.
// Java Program to Illustrate Method Overloading
// By Changing Data Types of the Parameters
// Importing required classes
import java.io.*;

// Class 1
// Helper class
class Product {
// Multiplying three integer values
public int Prod(int a, int b, int c)
{
int prod1 = a * b * c;
return prod1;
}
// Multiplying three double values.
public double Prod(double a, double b, double c)
{
double prod2 = a * b * c;
return prod2;
}
}
class GFG {
public static void main(String[] args)
{
Product obj = new Product();

int prod1 = obj.Prod(1, 2, 3);


System.out.println(
"Product of the three integer value :" + prod1);
double prod2 = obj.Prod(1.0, 2.0, 3.0);
System.out.println(
"Product of the three double value :" + prod2);
}
}
Output
Product of the three integer value :6
Product of the three double value :6.0

3. Changing the Order of the Parameters of Methods


Method overloading can also be implemented by rearranging the parameters of two or more overloaded
methods. For example, if the parameters of method 1 are (String name, int roll_no) and the other method is
(int roll_no, String name) but both have the same name, then these 2 methods are considered to be
overloaded with different sequences of parameters.
// Java Program to Illustrate Method Overloading
// By changing the Order of the Parameters

// Importing required classes


import java.io.*;

// Class 1
// Helper class
class Student {
// Method 1
public void StudentId(String name, int roll_no)
{
System.out.println("Name :" + name + " "
+ "Roll-No :" + roll_no);
}

// Method 2
public void StudentId(int roll_no, String name)
{
// Again printing name and id of person
System.out.println("Roll-No :" + roll_no + " "
+ "Name :" + name);
}
}

// Class 2
// Main class
class GFG {
// Main function
public static void main(String[] args)
{
// Creating object of above class
Student obj = new Student();

// Passing name and id


// Note: Reversing order
obj.StudentId("Spyd3r", 1);
obj.StudentId(2, "Kamlesh");
}
}
Output
Name :Spyd3r Roll-No :1
Roll-No :2 Name :Kamlesh

Advantages of Method Overloading


 Method overloading improves the Readability and reusability of the program.
 Method overloading reduces the complexity of the program.
 Using method overloading, programmers can perform a task efficiently and effectively.
 Using method overloading, it is possible to access methods performing related functions with
slightly different arguments and types.
 Objects of a class can also be initialized in different ways using the constructors.

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
Usage of Java Method Overriding
1. Method overriding is used to provide the specific implementation of a method that is already
provided by its superclass.
2. Method overriding is used for runtime polymorphism.
3. Method overriding allows subclasses to reuse and build upon the functionality provided by their
superclass, reducing redundancy and promoting modular code design.
4. Subclasses can override methods to tailor them to their specific needs or to implement specialized
behavior that is unique to the subclass.
5. Method overriding enables dynamic method dispatch, where the actual method implementation to
be executed is determined at runtime based on the type of object, supporting flexibility and
polymorphic behavior.

Rules for Java Method Overriding


1. Same Method Name: The overriding method in the subclass must have the same name as the
method in the superclass that it is overriding.
2. Same Parameters: The overriding method must have the same number and types of parameters as
the method in the superclass. This ensures compatibility and consistency with the method signature
defined in the superclass.
3. IS-A Relationship (Inheritance): Method overriding requires an IS-A relationship between the
subclass and the superclass. This means that the subclass must inherit from the superclass, either
directly or indirectly, to override its methods.
4. Same Return Type or Covariant Return Type: The return type of the overriding method can be the
same as the return type of the overridden method in the superclass, or it can be a subtype of the
return type in the superclass. This is known as the covariant return type, introduced in Java 5.
5. Access Modifier Restrictions: The access modifier of the overriding method must be the same as or
less restrictive than the access modifier of the overridden method in the superclass. Specifically, a
method declared as public in the superclass can be overridden as public or protected but not as
private. Similarly, a method declared as protected in the superclass can be overridden as protected
or public but not as private. A method declared as default (package-private) in the superclass can be
overridden with default, protected, or public, but not as private.
6. No Final Methods: Methods declared as final in the superclass cannot be overridden in the
subclass. This is because final methods cannot be modified or extended.
7. No Static Methods: Static methods in Java are resolved at compile time and cannot be overridden.
Instead, they are hidden in the subclass if a method with the same signature is defined in the
subclass.

Example
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
}
}

Output
Animals can move
Dogs can walk and run

Java Method Overriding: Using the super Keyword


When invoking a superclass version of an overridden method the super keyword is used.
Example: Using the super Keyword

class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal b = new Dog(); // Animal reference but Dog object
b.move(); // runs the method in Dog class
}
}
Output
Animals can move
Dogs can walk and run

Abstract Class in Java


Java abstract class is a class that can not be instantiated by itself, it needs to be subclassed by another class
to use its properties. An abstract class is declared using the “abstract” keyword in its class definition.
Syntax of Abstract Classes
public abstract class Shape {
public abstract double area();
public void display() {
System.out.println("This is a shape.");
}
}
Key Features of Abstract Classes
Abstract Methods: Abstract classes can have abstract methods, which are declared without a body.
Subclasses must provide concrete implementations for these methods.
Concrete Methods: Abstract classes can also contain concrete methods with defined behavior. Subclasses
inherit these methods along with their implementations.
Cannot be Instantiated: Abstract classes cannot be instantiated directly. They serve as a blueprint for other
classes and must be extended to be used.
Can Have Constructors: Abstract classes can have constructors, which are invoked when a subclass object is
created. These constructors are used to initialize the state of the abstract class.

Abstract classes are beneficial in various scenarios, including:


Code Reusability: Abstract classes facilitate code reuse by allowing common methods to be implemented
once and inherited by multiple subclasses.
Defining a Common Interface: Abstract classes can define a common interface for a group of related
classes, ensuring consistency in their structure and behavior.
Enforcing Method Implementation: Abstract classes can enforce the implementation of certain methods by
declaring them as abstract, thereby ensuring that subclasses provide necessary functionality.
Dynamic Method Dispatch in Java
 Dynamic method dispatch is also known as run time polymorphism.
 It is the process through which a call to an overridden method is resolved at runtime.
 This technique is used to resolve a call to an overridden method at runtime rather than compile
time.
 To properly understand Dynamic method dispatch in Java, it is important to understand the concept
of upcasting because dynamic method dispatch is based on upcasting.
Example to demonstrate the use of Dynamic method dispatch :
 In the below code, we've created two classes: Phone & SmartPhone.
 The Phone is the parent class and the SmartPhone is the child class.
 The method on() of the parent class is overridden inside the child class.
 Inside the main() method, we've created an object obj of the Smartphone() class by taking the
reference of the Phone() class.
 When obj.on() will be executed, it will call the on() method of the SmartPhone() class because the
reference variable obj is pointing towards the object of class SmartPhone().

class Phone{
public void showTime(){
System.out.println("Time is 8 am");
}
public void on(){
System.out.println("Turning on Phone...");
}
}

class SmartPhone extends Phone{


public void music(){
System.out.println("Playing music...");
}
public void on(){
System.out.println("Turning on SmartPhone...");
}
}
public class CWH {
public static void main(String[] args) {

Phone obj = new SmartPhone(); // Yes it is allowed


// SmartPhone obj2 = new Phone(); // Not allowed

obj.showTime();
obj.on();
// obj.music(); Not Allowed
}
}
Output :
Time is 8 am
Turning on SmartPhone...
Note: The data members can’t achieve the run time polymorphism.

final Keyword in Java


The final Keyword in Java is used as a non-access
modifier applicable only to a variable, a method, or a class.
It is used to restrict a user in Java.
The following are different contexts where the final is used:
1. Variable
2. Method
3. Class
Java Final Variable
When a variable is declared with the final keyword, its value can’t be changed, essentially, a constant.
This also means that you must initialize a final variable.
If the final variable is a reference, this means that the variable cannot be re-bound to reference another
object, but the internal state of the object pointed by that reference variable can be changed i.e. you can
add or remove elements from the final array or final collection.
It is good practice to represent final variables in all uppercase, using underscore to separate words.
Example:
public class ConstantExample {
public static void main(String[] args) {
// Define a constant variable PI
final double PI = 3.14159;

// Print the value of PI


System.out.println("Value of PI: " + PI);
}
}

Output:
Value of PI: 3.14159

Different Methods of Using Final Variable


Let’s see different methods that we can use final variable in Java.
1. final Variable
Example:
// Final variable
final int THRESHOLD = 5;
2. Blank final Variable
Example:
// Blank final variable
final int THRESHOLD;
3. Static final Variable
Example:
// Final static variable PI
static final double PI = 3.141592653589793;
4. Static Blank final Variable
Example:
// Blank final static variable
static final double PI;

Java Final classes


When a class is declared with the final keyword in Java, it is called a final class. A final class cannot
be extended(inherited).
There are two uses of a final class:
Usage 1: One is definitely to prevent inheritance, as final classes cannot be extended. For example,
all Wrapper Classes like Integer, Float, etc. are final classes. We can’t extend them.
final class A
{
// methods and fields
}
// The following class is illegal
class B extends A
{
// COMPILE-ERROR! Can't subclass A
}
Usage 2: The other use of final with classes is to create an immutable class like the predefined String class.
One can not make a class immutable without making it final.
Java Final Method
When a method is declared with final keyword, it is called a final method in Java. A final method cannot
be overridden.
The Object class does this—a number of its methods are final. We must declare methods with the final
keyword for which we are required to follow the same implementation throughout all the derived classes.
Illustration: Final keyword with a method
class A
{
final void m1()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void m1()
{
// Compile-error! We can not override
System.out.println("Illegal!");
}
}
Advantages of final Keyword in Java:
The final keyword in Java provides several advantages, including:
 Ensuring immutability: When a variable or reference is marked as final, its value cannot be changed
once it is assigned. This helps ensure that data is immutable and cannot be accidentally or
maliciously modified.
 Improving performance: The use of the final can sometimes help improve performance, as the Java
Virtual Machine (JVM) can optimize code more effectively when it knows that certain values or
references cannot be changed.
 Making code easier to understand: By declaring variables, methods, or classes as final, developers
can make their code easier to understand and reason about. When a value or reference is marked
as final, it is clear that it will not change, which can simplify code analysis and debugging.
 Promoting code reuse: By declaring methods as final, developers can prevent subclasses from
overriding them. This can help promote code reuse and reduce duplication, as subclasses must use
the parent class’s implementation of the method.
 Enhancing security: The use of final can help enhance security by preventing malicious code from
modifying sensitive data or behavior
Packages in Java
A package is a namespace that organizes a set of related classes and interfaces. Packages are used to
prevent name clashes and to control the access of classes, interfaces, and methods.
Basic Definition:
package com.example.utils;
In the above example, `com.example.utils` is a package that could contain utility classes related to an
application. Classes inside the package can be imported and used by other classes.

Uses of Packages
1. Organizing Code: Packages help group similar functionality into modules. For example, all database-
related classes can go into a `com.example.database` package.
2. Avoiding Naming Conflicts: In large projects, it’s possible to have classes with the same names. Packages
provide namespaces, so two classes with the same name can exist in different packages.
3. Access Control: Java packages provide access control mechanisms. Classes, methods, and fields can have
package-level visibility.
4. Reusability: Code can be organized into packages that can be reused across projects.

Types of Packages in Java


Java has two types of packages:
1. Built-in Packages: These are provided by the Java API (e.g., `java.util`, `java.io`, `java.lang`).
2. User-defined Packages: These are created by users to organize their classes and interfaces.

How to Create a Package?


To create a package in Java, you use the `package` keyword. The package statement must be the first line in
the source file (excluding comments).
Creating a Package:
// File: com/example/HelloWorld.java
package com.example;
public class HelloWorld {
public void greet() {
System.out.println("Hello from the com.example package!");
}
}
In this example:
- The `package com.example;` statement defines that the class `HelloWorld` belongs to the `com.example`
package.
- The folder structure should mirror the package name (`com/example/`).

Accessing Classes from Packages


To access a class from a package, the fully qualified name of the class (including the package name) should
be used, or the class should be imported.

Accessing Without Import:


com.example.HelloWorld hello = new com.example.HelloWorld();
hello.greet();

Accessing With Import:


You can import the class to avoid writing the full package name every time:
import com.example.HelloWorld;
public class Main {
public static void main(String[] args) {
HelloWorld hello = new HelloWorld();
hello.greet();
}
}

Importing Packages
Java provides the `import` statement to import classes or entire packages.
1. Importing a Single Class:
import com.example.HelloWorld;
2. Importing All Classes in a Package:
import com.example.*;
In the second example, all classes within the `com.example` package will be imported.

Sub-packages in Java
Java supports sub-packages, which are simply packages within other packages. There is no special syntax for
sub-packages; they are treated like regular packages, but the hierarchy is created by adding dots in the
package name.
Example:
package com.example.utils;
The `utils` package is a sub-package of `com.example`.
You can nest packages as deeply as required:
package com.example.database.connection;
This would represent a `connection` package under `database` under `com.example`.

Package Naming Conventions


Java follows certain conventions for naming packages to ensure uniqueness and clarity:
1. Reverse Domain Name: Use your domain name in reverse as the base of your package names. For
example, if your domain is `example.com`, start your package with `com.example`.
2. Lowercase Names: Use lowercase letters to avoid conflicts with class names.
3. Meaningful Names: Use descriptive and meaningful names to reflect the content of the package.
Example:
package com.mycompany.product.service;

Java Built-in Packages


Java comes with several built-in packages that provide a wide range of functionalities. Some common built-
in packages are:
- java.lang: Provides classes fundamental to the Java language (automatically imported).
- java.util: Contains utility classes, including collections framework, date, time facilities, and more.
- java.io: Contains classes for input/output operations (e.g., file handling).
- java.net: Contains classes for networking operations.
- java.sql: Contains classes for database access and processing.
Example of Using Built-in Packages:
import java.util.ArrayList;
public class BuiltInExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
System.out.println(list);
}
}

Example Program Using Packages


Here’s a full example of creating and using user-defined packages.
Step 1: Define a Package
Create a file `com/example/greetings/Greeter.java`:
package com.example.greetings;
public class Greeter {
public void sayHello() {
System.out.println("Hello from the Greeter class!");
}
}
Step 2: Create Another Class to Use This Package
Create another file in a different package `com/example/app/MainApp.java`:
package com.example.app;
// Importing the Greeter class from com.example.greetings
import com.example.greetings.Greeter;
public class MainApp {
public static void main(String[] args) {
Greeter greeter = new Greeter();
greeter.sayHello();
}
}
Step 3: Compiling and Running
To compile and run this example, follow these steps:
1. Compile:
Navigate to the root directory and compile both files:
javac com/example/greetings/Greeter.java
javac com/example/app/MainApp.java
2. Run:
Run the `MainApp` class:
java com.example.app.MainApp
Output:
Hello from the Greeter class!

Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java
interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a
method body.
o Java Interface also represents the IS-A relationship.
o It cannot be instantiated just like the abstract class.
o Since Java 8, we can have default and static methods in an interface.
o Since Java 9, we can have private methods in an interface.

Use of Java interface


There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

Declaration of Java interface


An interface is declared by using the interface keyword. It provides total abstraction; means all the methods
in an interface are declared with the empty body, and all the fields are public, static and final by default. A
class that implements an interface must implement all the methods declared in the interface.

Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
Example:
interface Animal {
void eat();
void sleep();
}
In this example, the Animal interface declares two method signatures: eat() and sleep(). Any class
implementing the Animal interface must provide concrete implementations for these methods.

Relationship Between Classes and Interfaces


As shown in the figure given below, a class extends another class, an interface extends another interface,
but a class implements an interface.

Java Interface Example


In this example, the Printable interface has only one method, and its implementation is provided in the A6
class.

File Name: InterfaceExample.java


interface printable{
void print();
}
class InterfaceExample implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
InterfaceExample obj = new InterfaceExample();
obj.print();
}
}
Output:
Hello

“implements” Keyword in Java


In Java, the implements keyword is used to implement an interface. An interface is a special type of class
which implements a complete abstraction and only contains abstract methods. To access the interface
methods, the interface must be “implemented” by another class with the implements keyword and the
methods need to be implemented in the class which is inheriting the properties of the interface. Since an
interface is not having the implementation of the methods, a class can implement any number of interfaces
at a time.
Example: Below example demonstrating the use of implements keyword in java.
// Defining an interface
interface One {
public void methodOne();
}

// Defining the second interface


interface Two {
public void methodTwo();
}
// Implementing the two interfaces
class Three implements One, Two {
public void methodOne()
{
// Implementation of the method
}
public void methodTwo()
{

// Implementation of the method


}
}

“extends” Keyword in Java


In Java, the extends keyword is used to indicate that the class which is being defined is derived from the
base class using inheritance. So basically, extends keyword is used to extend the functionality of the parent
class to the subclass. In Java, multiple inheritances are not allowed due to ambiguity. Therefore, a class can
extend only one class to avoid ambiguity.
Example: Below example demonstrating the use of extends keyword in java.
class One {
public void methodOne()
{
// Some Functionality
}
}
class Two extends One {
public static void main(String args[])
{
Two t = new Two();
// Calls the method one
// of the above class
t.methodOne();
}
}

Java Exception Handling


Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms
like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc.
Java try and catch
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
}
consider the following example:
This will generate an error, because myNumbers[10] does not exist.

public class Main {


public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}
The output will be something like this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Main.main(Main.java:4)

If an error occurs, we can use try...catch to catch the error and execute some code to handle it:
Example
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

The output will be:


Something went wrong.

Finally
The finally statement lets you execute code, after try...catch, regardless of the result:

Example
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}

The output will be:


Something went wrong.
The 'try catch' is finished.

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,
etc:
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print "Access granted":
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}

public static void main(String[] args) {


checkAge(15); // Set age to 15 (which is below 18...)
}
}
The output will be:

Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
If age was 20, you would not get an exception:

Example
checkAge(20);
The output will be:
Access granted - You are old enough!

Built-in Exceptions in Java


Java defines several exception classes inside the standard package java.lang.

The most general of these exceptions are subclasses of the standard type RuntimeException. Since java.lang
is implicitly imported into all Java programs, most exceptions derived from RuntimeException are
automatically available.
Types of Java Built-in Exceptions
Built-in Exceptions in Java are categorized into two categories Checked Exceptions and Unchecked
Exceptions.

Checked Exceptions: The checked exceptions are handled by the programmer during writing the code, they
can be handled using the try-catch block. These exceptions are checked at compile-time.
Unchecked Exceptions: The unchecked exceptions are not handled by the programmer. These exceptions
are thrown on run-time. Some of the unchecked exceptions are NullPointerException,
ArrayIndexOutOfBoundsException, ArithmeticException, etc.

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.
Sr.No. Exception & Description

1 ArithmeticException
Arithmetic error, such as divide-by-zero.
// Java program to demonstrate
// ArithmeticException
class ArithmeticException_Demo {
public static void main(String[] args) {
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
System.out.println("Result = " + c);
} catch (ArithmeticException e) {
System.out.println("Can't divide a number by 0");
}
}
}
Output
Can't divide a number by 0

2 ArrayIndexOutOfBoundsException - Array index is out-of-bounds.

3 ArrayStoreException - Assignment to an array element of an incompatible type.

4 ClassCastException - Invalid cast.

5 IllegalArgumentException - Illegal argument used to invoke a method.

6 IllegalMonitorStateException - Illegal monitor operation, such as waiting on an unlocked thread.

7 IllegalStateException - Environment or application is in incorrect state.

8 IllegalThreadStateException -Requested operation not compatible with the current thread state.

9 IndexOutOfBoundsException - Some type of index is out-of-bounds.

10 NegativeArraySizeException - Array created with a negative size.

11 NullPointerException - Invalid use of a null reference.

12 NumberFormatException - Invalid conversion of a string to a numeric format.

13 SecurityException - Attempt to violate security.

14 StringIndexOutOfBounds - Attempt to index outside the bounds of a string.

15 UnsupportedOperationException - An unsupported operation was encountered.

16 ClassNotFoundException - Class not found.

CloneNotSupportedException - Attempt to clone an object that does not implement the Cloneable
17
interface.

18 IllegalAccessException - Access to a class is denied.

19 InstantiationException - Attempt to create an object of an abstract class or interface.

20 InterruptedException - One thread has been interrupted by another thread.

21 NoSuchFieldException - A requested field does not exist.

22 NoSuchMethodException - A requested method does not exist.

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.
Example
import java.util.Scanner;

class NotEligibleException extends Exception{


NotEligibleException(String msg){
super(msg);
}
}

class VoterList{
int age;
VoterList(int age){
this.age = age;
}

void checkEligibility() {
try {
if(age < 18) {
throw new NotEligibleException("Error: Not eligible for vote due to under age.");
}
System.out.println("Congrates! You are eligible for vote.");
}
catch(NotEligibleException nee) {
System.out.println(nee.getMessage());
}
}
public static void main(String args[]) {

Scanner input = new Scanner(System.in);


System.out.println("Enter your age in years: ");
int age = input.nextInt();
VoterList person = new VoterList(age);
person.checkEligibility();
}
}
When we run this code, it produce the following output.

You might also like