0% found this document useful (0 votes)
31 views99 pages

All in One Oop

Uploaded by

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

All in One Oop

Uploaded by

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

GAMBELLA UNIVERSITY

FACILTY OF NATURAL AND COMPUTATIONAL SCIENCE

DEPARTMENT OF COMPUTER SCIENCE

Exit Exam Tutorial Module

Object Oriented Programming

By

Eyoas Atnafu (MSc)

Prepared by Eyoas A. Page 1


Objectives

To teach the student the concepts of object oriented and procedure programming

To differentiate between functions, classes and objects

To learn to overload functions and operators

To know Basic concepts of Object Oriented Programming,

To know the principles of OOP

Outcomes

To differentiate object oriented programming and procedural programming.

To construct classes, functions and objects

To implement the constructors, abstract and inheritance

To apply exception handling and generic programming

Prepared by Eyoas A. Page 2


Chapter 1: Introduction to Object-Oriented Programming

Introduction

What are the four important Principle of OOP?

Object-oriented programming (OOP) is a programming paradigm based upon objects (having


both data and methods) that aims to incorporate the advantages of modularity and reusability.
Objects, which are usually instances of classes, are used to interact with one another to design
applications and computer programs.

The important features of object–oriented programming are −

 Bottom–up approach in program design


 Programs organized around objects, grouped in classes
 Focus on data with methods to operate upon object’s data
 Interaction between objects through functions
 Reusability of design through creation of new classes by adding features to existing
classes

Some examples of object-oriented programming languages are C++, Java, Smalltalk, Delphi, C#,
Perl, Python, Ruby, and PHP.

Grady Booch has defined object–oriented programming as “a method of implementation in


which programs are organized as cooperative collections of objects, each of which represents an
instance of some class, and whose classes are all members of a hierarchy of classes united via
inheritance relationships”.

1.1. Types of programming paradigms


Programming paradigms are different ways or styles in which a given program or programming
language can be organized. Each paradigm consists of certain structures, features, and opinions
about how common programming problems should be tackled.
Programming paradigm is an approach to solve problem using some programming language or
also we can say it is a method to solve a problem using tools and techniques that are available
to us following some approach.
There are several kinds of major programming paradigms:

1. Imperative
2. Logical
3. Functional
4. Object-Oriented

Imperative programming paradigm: It is one of the oldest programming paradigm. It


features close relation to machine architecture. It is based on Von Neumann architecture. It

Prepared by Eyoas A. Page 3


works by changing the program state through assignment statements. It performs step by step
task by changing state. The main focus is on how to achieve the goal. The paradigm consist of
several statements and after execution of all the result is stored.
Advantages:
1. Very simple to implement
2. It contains loops, variables etc.
Disadvantage:
1. Complex problem cannot be solved
2. Less efficient and less productive
3. Parallel programming is not possible
Exam: C, Fortran, Basic

Logical Paradigm

The Logical Paradigm takes a declarative approach to problem-solving. Various logical


assertions about a situation are made, establishing all known facts. Then queries are made. The
role of the computer becomes maintaining data and logical deduction. In logic programming, we
have a knowledge base, which we know before and along with the question and knowledge
base, which is given to machine, it produces result.

Exam: Prolog

Functional Paradigm
The Functional Programming paradigm views all subprograms as functions in the mathematical
sense-informally; they take in arguments and return a single solution. The solution returned is
based entirely on the input, and the time at which a function is called has no relevance. The
computational model is therefore one of function application and reduction.

Languages
The functional programming paradigms has its roots in mathematics and it is language
independent. The key principle of this paradigm is the execution of series of mathematical
functions. The central model for the abstraction is the function which are meant for some
specific computation and not the data structure. Data are loosely coupled to functions. The
function hide their implementation. Function can be replaced with their values without
changing the meaning of the program.

Exam: Perl, JavaScript, Hascell, Scala

Advantages
The following are desirable properties of a functional language:

 The high level of abstraction, especially when functions are used, supresses many of the
details of programming and thus removes the possibility of committing many classes of
errors;

Prepared by Eyoas A. Page 4


 The lack of dependence on assignment operations, allowing programs to be evaluated in
many different orders. This evaluation order independence makes function-oriented
languages good candidates for programming massively parallel computers;
 The absence of assignment operations makes the function-oriented programs much more
amenable to mathematical proof and analysis than are imperative programs, because
functional programs possess referential transparency.

Disadvantages

 Perhaps less efficiency


 Problems involving many variables or a lot of sequential activity are sometimes easier to
handle imperatively or with object-oriented programming.

Object Oriented Paradigm


The program is written as a collection of classes and object which are meant for
communication. The smallest and basic entity is object and all kind of computation is
performed on the objects only. More emphasis is on data rather procedure. It can handle almost
all kind of real life problems which are today in scenario.

Objects are organized into classes, from which they inherit methods and equivalent variables.
The object-oriented paradigm provides key benefits of reusable code and code extensibility.

Advantages:
 Data security
 Inheritance
 Code reusability
 Flexible and abstraction is also present

1.2 Principles of Object-Oriented Programming


Object-Oriented Principles mainly include the 4 pillars that together make the OOP a very
powerful concept. That is –

1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism

Abstraction

Abstraction can be defined as hiding internal implementation and showing only the required
features or set of services that are offered. This is the most essential part of Object-Oriented
programming.

Let’s understand with the help of an example –

Prepared by Eyoas A. Page 5


Example 1 – We all have been using ATMs. And if we want to withdraw the money from that
then we simply interact with the Use Interface Screen where we have been asking for details.

As a user, we only want that I can use that ATM for the services. We are not interested in
knowing the internal implementation that what is the process happening inside the ATM
Machine like getting card details, validation, etc kind of things. We only have been provided an
interface to interact with that and simply ask for the work. And the internal implementation we
don’t need to know. So that is the Abstraction.

Explanation-

The above image shows the GUI screen of the ATM. In this when we want to withdraw then we
simply use that. For the implementation part, we don’t care.

The same concept is applicable in the programming implementation of the Abstraction. Although
different programming has a different syntax of implementation of Abstraction. But the most
popular programming languages like JAVA use a keyword called abstract which applies to the
class and methods to make a class abstract and achieve abstraction. And it can also be achieved
using the interfaces in java.

C++ achieves it by grouping the attributes and using an access specifier allowing what data is to
be visible outside.

Access Specifiers are the keywords that state, from where the (attributes and methods) of a class
can be accessed. For example – private can only be accessible within the class, the public can
be accessed from anywhere, etc.

Similarly, other programming languages follow their own implementation for achieving
abstraction.

Features of Abstraction –

1. Security- With Abstraction, the Outside persons don’t know the internal implementation
so it makes the classes more secure, so the unauthorized user will not have access to the
data.
2. Easy Enhancement- Suppose in the future we want to change the logic of the
implementation in class, So we don’t have to change the entire external logic which is

Prepared by Eyoas A. Page 6


there for the user. Just we need to make changes for the methods and it will not affect the
functionality.
3. Improves Easiness- It helps to use the features without knowing implementation so it
improves easiness for the users to use that.
4. Maintainability will improve- Without affecting the user, it can able to perform any
types of changes internally. SO maintainability will improve.

Encapsulation

Encapsulation can be defined as the binding of data and attributes or methods and data members
in a single unit. In classes, we have Data and attributes that perform operations on that data.
So according to the OOPs principle of Encapsulation, that data can be merged into a single unit.
Encapsulation enhances more security of the data as everything related to a single task must be
grouped and access to the data is given as per need.

And this can be achieved using the concept of Data Hiding.

Encapsulation = Data Hiding + Abstraction.

Data Hiding – It means hiding the data of the class and restricting access to the outside
world. Example – Using the access specifier keywords like private that restricts the data to only
accessible and modifiable in the same class. Outside users can not access the data.

Let’s understand with the help of an example-

Example 1- In the market, Capsules are available to cure different medical problems. Consider
capsule for fever. Now in that capsules, there are different compositions are grouped to make a
complete medicine that cures fever. So the grouping of that compositions into a single unit in the
capsule is a form of encapsulation. Here, consider fever as data, and the capsule as the operations
on the data. So everything is grouped here.

Explanation- In the above image, all the dots represent the compositions for curing the fever (as
per the example). And these are grouped into a capsule. Similarly in programming, when there
are multiple operations related to a particular data are present, then grouping that into a simple
unit is Encapsulation.

Example 2- In a car, we have all the required things to make a car complete. Like engines, gear
shift, Wheels, etc, and these are grouped into a single body that makes a car. It is not like the
wheels are not attached to the car, Engines are misplaced and dragged outside, etc. Everything is

Prepared by Eyoas A. Page 7


grouped into a single body. So in the OOP Principle also the same principle applies that
whatever operations are there for a particular group, must be capsuled to a single unit.

Explanation- In the image we can see that the car has an engine, steering to control, gear shift,
paddles to race and stop the car are present, and these are grouped into a complete car.
So we want the same things in programming also, And that’s what OOP Principle makes it
possible. Similarly, if we take an example more specific to programming then we can state an
example of a LinkedList. We create a node that contains data and this node is related to the
LinkedList class. And Operation on that node like – Add, Delete, Search, etc are grouped into a
single class.

Features of Encapsulation –

1. It provides extra security by the concept of Data Hiding.


2. It groups the data and operation in that data into a single unit.
3. It attaches an extra security layer to the data and allows to access data only to authorized
ones.

Inheritance

Inheritance is the method of acquiring features of the existing class into the new class. Suppose
there is a class, considered as the parent class, that has some methods associated with it. And we
declare a new class, considered as the child class, that has its own methods. So, when a child
class is inherited from the parent class then it will have all the methods associated with parent
class are available in the child class along with the child class own methods also. So that is
Inheritance.

There are two keywords involved in the inheritance – Base and Derived Class.

Base Class – It is also termed the parent class. It is the main class that has the basic properties
and methods which is defined.

Derived Class – This is the extension of the base class and it is also called the child class. It has
the properties and methods that are in the base class with its own features in it.

Polymorphism

Polymorphism is the most essential concept of the Object-Oriented Programming principle. It


has meaning ‘poly’ – many, ‘morph’ – forms. So polymorphism means many forms.

Prepared by Eyoas A. Page 8


In Object-Oriented Programming, any object or method has more than one name associated with
it. That is nothing but polymorphism.

For Objects – When any object can hold the reference of its parent object then it is a
polymorphism. To understand this concept more clear, let’s consider an example-

Example – We have Television from different companies, Let’s say Samsung TV, LG TV,
Xiaomi TV, etc. Now if we have to call it then mostly we don’t call it with its brand name. We
simply call it a Television, And it can be of a different brand. But in general, we call it television.
So this can be said to be polymorphism.

Object oriented programming paradigm allows decomposition of the system into the number of
entities called objects and then ties properties and function to these objects. An object’s
properties can be accessed only by the functions associated with that object but functions of one
object can access the function of other objects in the same cases using access specifiers.

Why do we need the object oriented programming paradigm?


Object-oriented programming paradigm methods enable us to create a set of objects that work
together to produce software that is better understandable and models their problem domains
than produced using traditional techniques. The software produced using object-oriented
programming paradigm is easier to adapt to the changing requirements, easier to maintain, create
modules of functionality, promote greater design, be more robust, and perform desired work
efficiently.

Object orientation techniques work more efficiently than traditional techniques due to the
following reasons.

 The higher level of abstraction: Top-down approach support abstraction at the Functional
level while object oriented approach support abstraction at the object level.
 The seamless transition among different software development phases: It uses the same
language for all phases, which reduces the level of complexity and redundancy makes
software development clear and robust.
 Good programming practice: The subroutine and attributes of a class are held together
tightly.
 Improves reusability: it supports inheritance due to which classes can be built from each
other. So only difference and enhancement between classes need to be designed and
coded. All the previous functionality remains as it is and can be used without change.

Basic concepts of object oriented programming paradigm

 Objects: Objects are nothing but real or abstract items that contain data to define the
object and methods that can manipulate that information. Thus the object is a
combination of data and methods.

Prepared by Eyoas A. Page 9


 Classes: Class is a group of objects that has the same properties and behavior and the
same kind of relationship and semantics. Once a class has been defined, we can create
any number of objects belonging to thy class. Objects are variables of the class. Each
object is associated with data of the type class with which they are created; this class is
the collection of objects of a similar type.
 Encapsulation: Encapsulation is the process of wrapping up data and functions into a
single unit. It is the most striking feature of the class. Data is not accessible to the outside
world, and only those functions which are wrapped in the class can access it. It provides
the interface between data objects and the program.
 Abstraction: Abstraction represents essential features. It does not represent the
background details and explanation. Classes use the concept of abstraction and define the
list of abstract attributes such as name, age, gender, etc., to operate on these attributes.
They encapsulate all the essential properties of the object.
 Inheritance: Inheritance is the property whereby one class extends another class’s
properties, including additional methods and variables. The original class is called a
superclass, and the class that exceeds the properties are called a subclass. As the subclass
contains all the data of the superclass, it is more specific.
 Polymorphism: In geek terms, polymorphism means the ability to take more than one
form. An operation may exhibit different behavior in a different instance. Behavior
depends on the types of data used for the operation.
 Messaging: Object oriented system consists of sets of objects that communicate with
each other. Object communicate with one another by sending and receiving data much
the same way as people pass messages to one another. A message for the object is a
request for execution of a method and, therefore, will invoke a method in the receiving
object that generates the desired result.

Java Development Environment


Java is owned and maintained by Oracle. It is available free for various platforms, including
Linux, Windows, and macOS. Since 1998 Java has gone through many versions. The current
version as of this writing is Java 18.
Everything needed to write Java programs — except for a text editor — is available for free in
the Java Development Kit (JDK).
There are also several integrated development environments (IDEs) available for developing
Java programs. IDEs integrate the JDK with a text editor, giving you everything you need in one
software package

If JDK as your development environment, The three basic steps are:


1. Edit the Java source code using a text editor.
2. Compile the Java source code into bytecode using javac .
3. Run the Java bytecode using java .

Prepared by Eyoas A. Page 10


Chapter 2: Java Class and Object
What is class in Java?

What is an Object in Java?


Objects and Classes in Java

In this page, we will learn about Java objects and classes. In object-oriented programming
technique, we design a program using objects and classes.

An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical
entity only.

object in Java

An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table,
car, etc. It can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.

An object has three characteristics:

o State: represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object such as deposit, withdraw,
etc.
o Identity: An object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. However, it is used internally by the JVM to identify
each object uniquely.

For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used
to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

What is a class in Java

A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.

Prepared by Eyoas A. Page 11


A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:


class <class_name>{
field;
method;
}
Instance variable in Java

A variable which is created inside the class but outside the method is known as an instance
variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when
an object or instance is created. That is why it is known as an instance variable.

Method in Java

In Java, a method is like a function which is used to expose the behavior of an object.

Advantage of Method
o Code Reusability
o Code Optimization

new keyword in Java

The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.

Object and Class Example: main within the class

In this example, we have created a Student class which has two data members id and name. We
are creating the object of the Student class by new keyword and printing the object's value.

Here, we are creating a main() method inside the class.

File: Student.java

//Java Program to illustrate how to define a class and fields


//Defining a Student class.
class Student{
//defining fields

Prepared by Eyoas A. Page 12


int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}

Output:

0
null
Object and Class Example: main outside the class

In real time development, we create classes and use it from another class. It is a better approach
than previous one. Let's see a simple example, where we are having main() method in another
class.

We can have multiple classes in different Java files or single Java file. If you define multiple
classes in a single Java source file, it is a good idea to save the file name with the class name
which has main() method.

File: TestStudent1.java

//Java Program to demonstrate having the main method in


//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output:
0
null

Prepared by Eyoas A. Page 13


3 Ways to initialize object

There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor

1) Object and Class Example: Initialization through reference

Initializing an object means storing data into the object. Let's see a simple example where we are
going to initialize the object through a reference variable.

File: TestStudent2.java

class Student{
int id;
String name;
}
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}

Output: 101 Sonoo

We can also create multiple objects and store information in it through reference variable.

File: TestStudent3.java

class Student{
int id;
String name;
}
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data

Prepared by Eyoas A. Page 14


System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);

Output:

101 Sonoo
102 Amit
2) Object and Class Example: Initialization through method

In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method. Here, we are displaying the state (data) of the
objects by invoking the displayInformation() method.

File: TestStudent4.java

class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);
}
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}

Output:

111 Karan
222 Aryan

3) Object and Class Example: Initialization through a constructor

We will learn about constructors in Java later.

Prepared by Eyoas A. Page 15


Object and Class Example: Employee

Let's see an example where we are maintaining records of employees.

File: TestEmployee.java

class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);
}
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}

Output:

101 ajeet 45000.0


102 irfan 25000.0
103 nakul 55000.0
Object and Class Example: Rectangle

There is given another example that maintains the records of Rectangle class.

File: TestRectangle1.java

class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;

Prepared by Eyoas A. Page 16


width=w;
}
void calculateArea(){System.out.println(length*width);
}
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}

Output:

55
45

What is a method in Java?

A method is a block of code or collection of statements or a set of code grouped together to


perform a certain task or operation. It is used to achieve the reusability of code. We write a
method once and use it many times. We do not require to write code again and again. It also
provides the easy modification and readability of code, just by adding or removing a chunk of
code. The method is executed only when we call or invoke it.

The most important method in Java is the main() method. If you want to read more about the
main() method, go through the link https://www.javatpoint.com/java-main-method.

Method Declaration

The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header, as we have
shown in the following figure.

Prepared by Eyoas A. Page 17


Method Signature: Every method has a method signature. It is a part of the method declaration.
It includes the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:

o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.

Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.

Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by its
name.

Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left the
parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be performed.
It is enclosed within the pair of curly braces.

Prepared by Eyoas A. Page 18


Naming a Method

While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a verb
followed by adjective or noun. In the multi-word method name, the first letter of each word must
be in uppercase except the first word. For example:

Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(), stringComparision()

It is also possible that a method has the same name as another method name in the same class, it
is known as method overloading.

Types of Method

There are two types of methods in Java:

o Predefined Method
o User-defined Method

Predefined Method

In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any
of the predefined methods in our program, a series of codes related to the corresponding method
runs in the background that is already stored in the library.

Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.

Let's see an example of the predefined method.

Demo.java

public class Demo


{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}

Prepared by Eyoas A. Page 19


Output:

The maximum number is: 9

In the above example, we have used three predefined methods main(), print(), and max(). We
have used these methods directly without declaration because they are predefined. The print()
method is a method of PrintStream class that prints the result on the console. The max() method
is a method of the Math class that returns the greater of two numbers.

In the above method signature, we see that the method signature has access specifier public,
non-access modifier static, return type int, method name max(), parameter list (int a, int b). In
the above example, instead of defining the method, we have just invoked the method. This is the
advantage of a predefined method. It makes programming less complicated.

Similarly, we can also see the method signature of the print() method.

User-defined Method

The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.

How to Create a User-defined Method

Let's create a user defined method that checks the number is even or odd. First, we will define
the method.

//user defined method


public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}

We have defined the above method named findevenodd(). It has a parameter num of type int.
The method does not return any value that's why we have used void. The method body contains
the steps to check the number is even or odd. If the number is even, it prints the number is even,
else prints the number is odd.

How to Call or Invoke a User-defined Method

Once we have defined a method, it should be called. The calling of a method in a program is
simple. When we call or invoke a user-defined method, the program control transfer to the called
method.

Prepared by Eyoas A. Page 20


import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from the user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}

In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the
control transfer to the method and gives the output accordingly.

Let's combine both snippets of codes in a single program and execute it.

EvenOdd.java

import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}

Output 1:

Prepared by Eyoas A. Page 21


Enter the number: 12
12 is even

Output 2:

Enter the number: 99


99 is odd

Let's see another program that return a value to the calling method.

In the following program, we have defined a method named add() that sum up the two numbers.
It has two parameters n1 and n2 of integer type. The values of n1 and n2 correspond to the value
of a and b, respectively. Therefore, the method adds the value of a and b and store it in the
variable s and returns the sum.

Addition.java

public class Addition


{
public static void main(String[] args)
{
int a = 19;
int b = 5;
//method calling
int c = add(a, b); //a and b are actual parameters
System.out.println("The sum of a and b is= " + c);
}
//user defined method
public static int add(int n1, int n2) //n1 and n2 are formal parameters
{
int s;
s=n1+n2;
return s; //returning the sum
}
}

Output:

The sum of a and b is= 24


Static Method

A method that has static keyword is known as static method. In other words, a method that
belongs to a class rather than an instance of a class is known as a static method. We can also
create a static method by using the keyword static before the method name.

Prepared by Eyoas A. Page 22


The main advantage of a static method is that we can call it without creating an object. It can
access static data members and also change the value of it. It is used to create an instance
method. It is invoked by using the class name. The best example of a static method is
the main() method.

Example of static method

Display.java

public class Display


{
public static void main(String[] args)
{
show();
}
static void show()
{
System.out.println("It is an example of static method.");
}
}

Output:

It is an example of a static method.


Instance Method

The method of the class is known as an instance method. It is a non-static method defined in
the class. Before calling or invoking the instance method, it is necessary to create an object of its
class. Let's see an example of an instance method.

InstanceMethodExample.java

public class InstanceMethodExample


{
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
}
int s;
//user-defined method because we have not used static keyword
public int add(int a, int b)
{
s = a+b;

Prepared by Eyoas A. Page 23


//returning the sum
return s;
}
}

Output:

The sum is: 25

There are two types of instance method:

o Accessor Method
o Mutator Method

Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor
method. We can easily identify it because the method is prefixed with the word get. It is also
known as getters. It returns the value of the private field. It is used to get the value of the private
field.

Example

public int getId()


{
return Id;
}

Mutator Method: The method(s) read the instance variable(s) and also modify the values. We
can easily identify it because the method is prefixed with the word set. It is also known
as setters or modifiers. It does not return anything. It accepts a parameter of the same data type
that depends on the field. It is used to set the value of the private field.

Example

public void setRoll(int roll)


{
this.roll = roll;
}
Example of accessor and mutator method

Student.java

public class Student


{
private int roll;
private String name;
public int getRoll() //accessor method

Prepared by Eyoas A. Page 24


{
return roll;
}
public void setRoll(int roll) //mutator method
{
this.roll = roll;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public void display()
{
System.out.println("Roll no.: "+roll);
System.out.println("Student name: "+name);
}
}

Abstract Method

The method that does not has method body is known as abstract method. In other words, without
an implementation is known as abstract method. It always declares in the abstract class. It
means the class itself must be abstract if it has abstract method. To create an abstract method, we
use the keyword abstract.

Syntax

abstract void method_name();


Example of abstract method

Demo.java

abstract class Demo //abstract class


{
//abstract method declaration
abstract void display();
}
public class MyClass extends Demo
{
//method impelmentation
void display()
{

Prepared by Eyoas A. Page 25


System.out.println("Abstract method?");
}
public static void main(String args[])
{
//creating object of abstract class
Demo obj = new MyClass();
//invoking abstract method
obj.display();
}
}

Output:

Abstract method...

Constructors in Java

In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the
memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor, and parameterized constructor.

Note: It is called constructor because it constructs the values at the time of object creation. It is
not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.

Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Prepared by Eyoas A. Page 26


Note: We can use access modifiers while declaring a constructor. It controls the object
creation. In other words, we can have private, protected, public or default constructor in Java.
Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:


1. <class_name>(){}

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of
object creation.

Example of default constructor


//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}

Output: Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default


constructor.

What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.

Example of default constructor that displays the default values


1. //Let us see another example of default constructor

Prepared by Eyoas A. Page 27


2. //which displays the default values
3. class Student3{
4. int id;
5. String name;
6. //method to display the value of id and name
7. void display(){System.out.println(id+" "+name);}
8.
9. public static void main(String args[]){
10. //creating objects
11. Student3 s1=new Student3();
12. Student3 s2=new Student3();
13. //displaying values of the object
14. s1.display();
15. s2.display();
16. }
17. }
Test it Now

Output:

0 null
0 null

Explanation:In the above class,you are not creating any constructor so compiler provides you a
default constructor. Here 0 and null values are provided by default constructor.

Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.

1. //Java Program to demonstrate the use of the parameterized constructor.


2. class Student4{
3. int id;
4. String name;
5. //creating a parameterized constructor
6. Student4(int i,String n){

Prepared by Eyoas A. Page 28


7. id = i;
8. name = n;
9. }
10. //method to display the values
11. void display(){System.out.println(id+" "+name);}
12.
13. public static void main(String args[]){
14. //creating objects and passing values
15. Student4 s1 = new Student4(111,"Karan");
16. Student4 s2 = new Student4(222,"Aryan");
17. //calling method to display the values of object
18. s1.display();
19. s2.display();
20. }
21. }

Output:

111 Karan
222 Aryan

Difference between constructor and method in Java

There are many differences between constructors and methods. They are given below.

Prepared by Eyoas A. Page 29


Java static keyword

The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to the
class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

1) Java static variable

If you declare any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property of all objects (which is
not unique for each object), for example, the company name of employees, college name
of students, etc.
o The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Understanding the problem without static variable


class Student{
int rollno;
String name;
String college="ITS";
}

Suppose there are 500 students in my college, now all instance data members will get memory
each time when the object is created. All students have its unique rollno and name, so instance
data member is good in such case. Here, "college" refers to the common property of all objects.
If we make it static, this field will get the memory only once.

Java static property is shared to all objects.


Example of static variable
//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable

Prepared by Eyoas A. Page 30


//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}
Output:
111 Karan ITS
222 Aryan ITS
2) Java static method

If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.

Example of static method


//Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}

Prepared by Eyoas A. Page 31


//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

this keyword in Java

There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.

Usage of Java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

Suggestion: If you are beginner to java, lookup only three usages of this keyword.

Prepared by Eyoas A. Page 32


1) this: to refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of ambiguity.

Understanding the problem without this keyword

Let's understand the problem if we don't use this keyword by the example given below:

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}

Output:

0 null 0.0
0 null 0.0

Prepared by Eyoas A. Page 33


In the above example, parameters (formal arguments) and instance variables are same. So, we
are using this keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword


class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}

Output:

111 ankit 5000.0


112 sumit 6000.0

If local variables(formal arguments) and instance variables are different, there is no need to use
this keyword like in the following program:

Program where this keyword is not required


class Student{
int rollno;
String name;
float fee;
Student(int r,String n,float f){
rollno=r;
name=n;
fee=f;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis3{
public static void main(String args[]){

Prepared by Eyoas A. Page 34


Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}

Output:

111 ankit 5000.0


112 sumit 6000.0
It is better approach to use meaningful names for variables. So we use same name for instance
variables and parameters in real time, and always use this keyword.

2) this: to invoke current class method

You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method. Let's see the
example

class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}
}

Output:

Prepared by Eyoas A. Page 35


hello n
hello m

3) this() : to invoke current class constructor

The this() constructor call can be used to invoke the current class constructor. It is used to reuse
the constructor. In other words, it is used for constructor chaining.

Calling default constructor from parameterized constructor:

class A{
A(){
System.out.println("hello a");
}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}
}

Output:

hello a
10

Calling parameterized constructor from default constructor:

class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}
}

Prepared by Eyoas A. Page 36


Output:
5
hello a
Real usage of this() constructor call

The this() constructor call should be used to reuse the constructor from the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see the
example given below that displays the actual use of this keyword.

class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis7{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}
}

Output:

111 ankit java 0.0


112 sumit java 6000.0
Rule: Call to this() must be the first statement in constructor.
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;

Prepared by Eyoas A. Page 37


}
Student(int rollno,String name,String course,float fee){
this.fee=fee;
this(rollno,name,course);//C.T.Error
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis8{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}
}

Output:

Compile Time Error: Call to this must be first statement in constructor


4) this: to pass as an argument in the method

The this keyword can also be passed as an argument in the method. It is mainly used in the event
handling. Let's see the example:

class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}

Output:

method is invoked
Application of this that can be passed as an argument:

In event handling (or) in a situation where we have to provide reference of a class to another one.
It is used to reuse one object in many methods.

Prepared by Eyoas A. Page 38


5) this: to pass as argument in the constructor call

We can pass the this keyword in the constructor also. It is useful if we have to use one object in
multiple classes. Let's see the example:

class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}

class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:10
6) this keyword can be used to return current class instance

We can return this keyword as an statement from the method. In such case, return type of the
method must be the class type (non-primitive). Let's see the example:

Syntax of this that can be returned as a statement


return_type method_name(){
return this;
}
Example of this keyword that you return as a statement from the method
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}

Prepared by Eyoas A. Page 39


}

Output:

Hello java
Access Modifiers in Java

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.

Understanding Java Access Modifiers

Access within within outside package by subclass outside


Modifier class package only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Prepared by Eyoas A. Page 40


Public Y Y Y Y

Let's understand the access modifiers in Java by a simple table.

1) Private

The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class, so
there is a compile-time error.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:

class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Note: A class cannot be private or protected except nested class.

2) Default

Prepared by Eyoas A. Page 41


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.

3) Protected

The protected access modifier is accessible within package and outside the package but through
inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package
is declared as protected, so it can be accessed from outside the class only through inheritance.

//save by A.java
package pack;

Prepared by Eyoas A. Page 42


public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello

4) Public

The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

Example of public access modifier

//save by A.java

package pack;
public class A{
public 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();
obj.msg();
}
}
Output:Hello

Java Access Modifiers with Method Overriding

If you are overriding any method, overridden method (i.e. declared in subclass) must not be more
restrictive.

Prepared by Eyoas A. Page 43


class A{
protected void msg(){System.out.println("Hello java");}
}

public class Simple extends A{


void msg(){System.out.println("Hello java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}
The default modifier is more restrictive than protected. That is why, there is a compile-time error

Encapsulation in Java

Encapsulation in Java is a process of wrapping code and data together into a single unit, for
example, a capsule which is mixed of several medicines.

We can create a fully encapsulated class in Java by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.

The Java Bean class is the example of a fully encapsulated class.

Advantage of Encapsulation in Java

By providing only a setter or getter method, you can make the class read-only or write-only. In
other words, you can skip the getter or setter methods.

It provides you the control over the data. Suppose you want to set the value of id which should
be greater than 100 only, you can write the logic inside the setter method. You can write the
logic not to store the negative numbers in the setter methods.

It is a way to achieve data hiding in Java because other class will not be able to access the data
through the private data members.

The encapsulate class is easy to test. So, it is better for unit testing.

The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and
fast to create an encapsulated class in Java.

Prepared by Eyoas A. Page 44


Simple Example of Encapsulation in Java

Let's see the simple example of encapsulation that has only one field with its setter and getter
methods.

File: Student.java

//A Java class which is a fully encapsulated class.


//It has a private data member and getter and setter methods.
package com.javatpoint;
public class Student{
//private data member
private String name;
//getter method for name
public String getName(){
return name;
}
//setter method for name
public void setName(String name){
this.name=name
}
}
File: Test.java
//A Java class to test the encapsulated class.
package com.javatpoint;
class Test{
public static void main(String[] args){
//creating instance of the encapsulated class
Student s=new Student();
//setting value in the name member
s.setName("vijay");
//getting value of the name member
System.out.println(s.getName());
}
}

Output:

vijay

Prepared by Eyoas A. Page 45


Chapter 3: Inheritance and Polymorphism
3.1 Inheritance

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).


o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
o 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.
o Reusability: As the name specifies, reusability is a mechanism which 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.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new
class is called child or subclass.

Prepared by Eyoas A. Page 46


Java Inheritance Example

Exam: As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is Programmer IS-A Employee. It means
that Programmer is a type of Employee.

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
Programmer salary is:40000.0
Bonus of programmer is:10000

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.

Prepared by Eyoas A. Page 47


Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}

Prepared by Eyoas A. Page 48


Output:

barking...
eating...
Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal
class, so there is a multilevel inheritance.

File: TestInheritance2.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output:

weeping...
barking...
eating...
Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.

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

Prepared by Eyoas A. Page 49


}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Output:

meowing...
eating...
Q) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.

onsider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A
and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time
error.

class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Output: Compile Time Error

Prepared by Eyoas A. Page 50


3.1 Java Type Casting

Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting:

 Widening Casting (automatically) - converting a smaller type to a larger type size


byte -> short -> char -> int -> long -> float -> double

 Narrowing Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char -> short -> byte

Widening Casting

Widening casting is done automatically when passing a smaller size type to a larger size type:

Example
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}}

Try it Yourself »

Narrowing Casting

Narrowing casting must be done manually by placing the type in parentheses in front of the
value:

Example
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int

Prepared by Eyoas A. Page 51


System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}
3.3 Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are related to
each other by inheritance.
Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from
another class. Polymorphism uses those methods to perform different tasks. This allows us to
perform a single action in different ways.
For example, think of a superclass called Animal that has a method called animalSound().
Subclasses of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own
implementation of an animal sound (the pig oinks, and the cat meows, etc.):
Example
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow");
}
}
Remember from the Inheritance chapter that we use the extends keyword to inherit from a class.
Now we can create Pig and Dog objects and call the animalSound() method on both of them:

Prepared by Eyoas A. Page 52


Example
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow");
}
}
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
Try it Yourself »

Why And When To Use "Inheritance" and "Polymorphism"?

Prepared by Eyoas A. Page 53


- It is useful for code reusability: reuse attributes and methods of an existing class when you
create a new class.
3.4 Java Method Overloading and Overriding
Method Overloading in Java

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand the
behavior of the method because its name differs.

So, we perform method overloading to figure out the program quickly.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In Java, Method Overloading is not possible by changing the return type of the method only.

) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for calling
methods.

class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){

Prepared by Eyoas A. Page 54


System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

Output:

22
33
2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.

class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}

Output:

22
24.9

Q) Why Method Overloading is not possible by changing the return type of method only?

In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:

class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}

Output:

Compile Time Error: method add(int,int) is already defined in class Adder

Prepared by Eyoas A. Page 55


System.out.println(Adder.add(11,11)); //Here, how can java determine which sum() method
should be called?
1. Note: Compile Time Error is better than Run Time Error. So, java compiler renders
compiler time error if you declare the same method having same parameters.
Can we overload java main() method?

Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls main() method which receives string array as arguments only. Let's
see the simple example:

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.

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.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class but
it has some specific implementation. The name and parameter of the method are the same, and
there is IS-A relationship between the classes, so there is method overriding.

//Java Program to illustrate the use of Java Method Overriding


//Creating a parent class.
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

Prepared by Eyoas A. Page 56


public static void main(String args[]){
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}

Output:

Bike is running safely


A real example of Java Method Overriding

Consider a scenario where Bank is a class that provides functionality to get the rate of interest.
However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS
banks could provide 8%, 7%, and 9% rate of interest.

Java method overriding is mostly used in Runtime Polymorphism which we will learn in next
pages.
//Java Program to demonstrate the real scenario of Java Method Overriding
//where three classes are overriding the method of a parent class.
//Creating a parent class.
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
//Test class to create objects and call the methods
class Test2{
public static void main(String args[]){

Prepared by Eyoas A. Page 57


SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Can we override static method?

No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will
learn it later.

Why can we not override static method?

It is because the static method is bound with class whereas instance method is bound with an
object. Static belongs to the class area, and an instance belongs to the heap area.

Can we override java main method?

No, because the main is a static method.

Difference between method overloading and method overriding in java

There are many differences between method overloading and method overriding in java. A list of
differences between method overloading and method overriding are given below:

No. Method Overloading Method Overriding

1) Method overloading is used to increase the Method overriding is used to provide


readability of the program. the specific implementation of the
method that is already provided by its
super class.

2) Method overloading is performed within class. Method overriding occurs in two


classes that have IS-A (inheritance)
relationship.

Prepared by Eyoas A. Page 58


3) In case of method overloading, parameter must be In case of method
different. overriding, parameter must be same.

4) Method overloading is the example of compile time Method overriding is the example
polymorphism. of run time polymorphism.

5) In java, method overloading can't be performed by Return type must be same or


changing return type of the method only. Return type covariant in method overriding.
can be same or different in method overloading. But
you must have to change the parameter.

3.5 Super Keyword in Java

The super keyword in Java is a reference variable which is used to refer immediate parent class
object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have same fields.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}

Prepared by Eyoas A. Page 59


Output:

black
white

In the above example, Animal and Dog both classes have a common property color. If we print
color property, it will print the color of current class by default. To access the parent property,
we need to use super keyword.

2) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}

Output:

eating...
barking...

In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given to
local.

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:

Prepared by Eyoas A. Page 60


class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}

Output:

animal is created
dog is created
Note: super() is added in each class constructor automatically by compiler if there is no super()
or this().

As we know well that default constructor is provided by compiler automatically if there is no


constructor. But, it also adds super() as the first statement.

Another example of super keyword where super() is provided by the compiler implicitly.

class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}}
Test it Now

Output:

animal is created
dog is created

Prepared by Eyoas A. Page 61


super example: real use

Let's see the real use of super keyword. Here, Emp class inherits Person class so all the
properties of Person will be inherited to Emp by default. To initialize all the property, we are
using parent class constructor from child class. In such way, we are reusing the parent class
constructor.

class Person{
int id;
String name;
Person(int id,String name){
this.id=id;
this.name=name;
}
}
class Emp extends Person{
float salary;
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
}}

Output:

1 ankit 45000

3.6 Object class in Java

The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.

The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, know as upcasting.

Let's take an example, there is getObject() method that returns an object but it can be of any type
like Employee,Student etc, we can use Object class reference to refer that object. For example:

Object obj=getObject();//we don't know what object will be returned from this method

Prepared by Eyoas A. Page 62


The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.

3.7 Abstract class in Java

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).

Before learning the Java abstract class, let's understand the abstraction in Java first.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to
the user.

Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.

Example of abstract class

abstract class A{}

Prepared by Eyoas A. Page 63


Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as an
abstract method.

Example of abstract method

abstract void printStatus();//no method body and abstract

Understanding the real scenario of Abstract class

In this example, Shape is the abstract class, and its implementation is provided by the Rectangle
and Circle classes.

Mostly, we don't know about the implementation class (which is hidden to the end user), and an
object of the implementation class is provided by the factory method.

A factory method is a method that returns the instance of the class. We will learn about the
factory method later.

In this example, if you create the instance of Rectangle class, draw() method of Rectangle class
will be invoked.

File: TestAbstraction1.java

abstract class Shape{


abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getshape() m
ethod
s.draw();
}
}
Output
drawing circle

Prepared by Eyoas A. Page 64


3.8 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.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

o t 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.

How to declare an 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.
}

Prepared by Eyoas A. Page 65


Internal addition by the compiler
The Java compiler adds public and abstract keywords before the interface method. Moreover, it
adds public, static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and the methods are public
and abstract.

The 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.

interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}

Prepared by Eyoas A. Page 66


}

Output:

Hello
Java Interface Example: Drawable

In this example, the Drawable interface has only one method. Its implementation is provided by
Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers. Moreover, it is used by
someone else. The implementation part is hidden by the user who uses the interface.

File: TestInterface1.java

//Interface declaration: by first user


interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
}}

Output:

drawing circle
Java Interface Example: Bank

Let's see another example of java interface which provides the implementation of Bank interface.

File: TestInterface2.java

interface Bank{
float rateOfInterest();
}
class SBI implements Bank{

Prepared by Eyoas A. Page 67


public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}

Output:

ROI: 9.15

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known


as multiple inheritance.

interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

Prepared by Eyoas A. Page 68


public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:Hello
Welcome
Q) Multiple inheritance is not supported through class in java, but it is possible by an interface,
why?

As we have explained in the inheritance chapter, multiple inheritance is not supported in the case
of class because of ambiguity. However, it is supported in case of an interface because there is
no ambiguity. It is because its implementation is provided by the implementation class. For
example:

interface Printable{
void print();
}
interface Showable{
void print();
}

class TestInterface3 implements Printable, Showable{


public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
}

Output:

Hello

As you can see in the above example, Printable and Showable interface have same methods but
its implementation is provided by class TestTnterface1, so there is no ambiguity.

Interface inheritance

A class implements an interface, but one interface extends another interface.

interface Printable{
void print();
}

Prepared by Eyoas A. Page 69


interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}

Output:

Hello
Welcome
Java 8 Default Method in Interface

Since Java 8, we can have method body in interface. But we need to make it default method.
Let's see an example:

File: TestInterfaceDefault.java

interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}

Output:

drawing rectangle
default method

Prepared by Eyoas A. Page 70


Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods. Since Java 8, it can have default and static
methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, static and Interface has only static and final variables.
non-static variables.

4) Abstract class can provide the implementation of Interface can't provide the implementation of
interface. abstract class.

5) The abstract keyword is used to declare abstract The interface keyword is used to declare
class. interface.

6) An abstract class can extend another Java class and An interface can extend another Java interface
implement multiple Java interfaces. only.

7) An abstract class can be extended using keyword An interface can be implemented using
"extends". keyword "implements".

8) A Java abstract class can have class members like Members of a Java interface are public by
private, protected, etc. default.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Prepared by Eyoas A. Page 71


Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).

Example of abstract class and interface in Java

Let's see a simple example where we are using interface and abstract class both.

//Creating interface that has 4 methods


interface A{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}

//Creating abstract class that provides the implementation of one method of A interface
abstract class B implements A{
public void c(){System.out.println("I am C");}
}

//Creating subclass of abstract class, now we need to provide the implementation of rest of the m
ethods
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}

//Creating a test class that calls the methods of A interface


class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}

Output:

I am a
I am b
I am c
I am d

Prepared by Eyoas A. Page 72


3.9 Java 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.

Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Simple example of java package

The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");

Prepared by Eyoas A. Page 73


}
}
How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename

For example

javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
The . represents the current folder.

How to access package from another package?

There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.

The import keyword is used to make the classes and interface of another package accessible to
the current package.

Prepared by Eyoas A. Page 74


Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public 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();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname


//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.

Prepared by Eyoas A. Page 75


It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.

Example of package by import fully qualified name


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be imported excluding
the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.

Note: Sequence of the program must be package then import then class.

Subpackage in java

Package inside the package is called the subpackage. It should be created to categorize the
package further.

Let's take an example, Sun Microsystem has definded a package named java that contains many
classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group
e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes
are for networking etc and so on. So, Sun has subcategorized the java package into subpackages
such as lang, net, io etc. and put the Input/Output related classes in io package, Server and
ServerSocket classes in net packages and so on.

Prepared by Eyoas A. Page 76


The standard of defining package is domain.company.package e.g. com.javatpoint.bean or
org.sssit.dao.
Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java

To Run: java com.javatpoint.core.Simple

Output:Hello subpackage

Prepared by Eyoas A. Page 77


Chapter 4: Exception Handling
Exceptions Overview
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
 A user has entered an invalid data
 A file that needs to be opened cannot be found
 A network connection has been lost in the middle of communications or the JVM has run
out of memory
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
Exception handling is a mechanism to handle runtime errors, so that normal flow of the
program can be maintained.
Exception Hierarchy:
Throwable is the super class

Advantages/Benefits of exceptional handling:


 Using exceptional handling we can separate the error handling code from normal code.
 Using exceptional handling we can differentiate the error types
 Normal flow of program can be maintained

Prepared by Eyoas A. Page 78


Types of Exception:
1. Checked exception
2. Unchecked exception
3. Error
Checked exceptions:
Checked exceptions are those exceptional conditions that are checked by compiler at the compile
time. A checked exception forces you to either use try-catch or throws. All exceptions except
Error, RuntimeException, and their subclasses are checked exceptions.
e.g. – IOException, SQLException etc.
Let's start by looking at some of the most common checked exceptions in Java.
1. ClassNotFoundException
The ClassNotFoundException happens when a required class cannot be found on the class path.
The most common situation where the ClassNotFoundException occurs is when an external
dependency is not available, which stems from application misconfiguration. In Maven-based
projects, for example, this would translate to a missing or misconfigured.
The easiest way to reproduce this error is to simply delete a required .class file of a previously-
running program. When the program attempts to make a call to a method inside the deleted .class
file, it will throw the ClassNotFoundException.
2. InvocationTargetException
The InvocationTargetException is related to the reflection functionality of Java and occurs when
trying to invoke a method or constructor that results in throwing an exception. To illustrate,
consider the following class:
public class Example {
public int divide(int numerator) {
return numerator / 0;
}
}
The divide() method includes an input number (numerator), but the denominator is fixed at zero,
which will produce a divide by zero error (ArithmeticException).
The InvocationTargetExceptioncode> error occurs when using reflection to invoke the method:

Prepared by Eyoas A. Page 79


Example example = new Example();
Method method = Example.class.getMethod("divide");
Exception exception = assertThrows(Example.class, () -> method.invoke(example));
Since the InvocationTargetException is in the reflection layer, the ArithmeticException is
wrapped inside this provided exception.
3. InterruptedException
Every thread has a boolean interrupt property used as an internal flag representing its interrupted
status. This property provides a way for threads to interrupt—or stop—other threads/tasks.
The InterruptedException is thrown when a thread that is working or sleeping is interrupted.
Throwing/catching this exception allows your code to know if and when a thread has been
stopped.
4. NoSuchMethodException
Like the InvocationTargetException (above), the NoSuchMethodException is related to the use
of reflection. This error stems from trying to access a provided method name that either does not
exist or is configured as a private method. Consider the simple example below:
public class Example {
public int divide(int numerator) {
return numerator / 0;
}
public int addOne(int number) {
return doSomethingPrivate(number);
}
private int doSomethingPrivate(int number) {
return number++;
}
}
The doSomethingPrivate() method is a private method and not visible in the following scenario:

Class c = Class.forName("Example");
Method method = c.getDeclaredMethod("doSomethingPrivate", parameterTypes);
method.invoke(objectToInvokeOn, params);

Prepared by Eyoas A. Page 80


As a result, it throws a NoSuchMethodException.
Unchecked exceptions:
Unchecked exceptions are those exceptional conditions that are not checked by compiler at the
compile time. Unchecked exceptions are checked at runtime. An unchecked exception not forces
you to either use try-catch or throws. RuntimeException and their subclasses are unchecked
exceptions. This Exception can be avoided by programmer.
e.g. – NullPointerException, ArithmeticException etc.
Unchecked Exceptions
Now let's look at some of the most common Unchecked exceptions in Java.
1. NullPointerException
A NullPointerException is thrown when a Java program attempts to process an object which
contains a null value.
public class Example {
public void doSomething() {
Integer number = null;
if (number > 0) {
System.out.println("Positive number");
}
}
}
In the example above, the number (Integer) object is null, so performing a simple evaluation will
throw a NullPointerException.
2. ArrayIndexOutOfBoundsException
The ArrayIndexOutOfBoundsException occurs while processing an array and asking for a
position that does not exist within the size of the array. Consider the following example:

public class Example {


public void processArray() {
List names = new ArrayList<>();
names.add("Eric");
names.add("Sydney");

Prepared by Eyoas A. Page 81


return names.get(5);
}
}
The names list contains two values, so 1 is the valid max index of this zero-based
structure. As a result, asking for the name at position 5 will return
an ArrayIndexOutOfBoundsException.
3. IllegalStateException
The IllegalStateException is thrown when a method is being called at an illegal or inappropriate
time. A common occurrence of this exception is thrown when attempting to remove an item from
the list while you are processing that list, as demonstrated below:
public class Example {
public void processArray() {
List names = new ArrayList<>();
names.add("Eric");
names.add("Sydney");
Iterator iterator = names.iterator();
while (iterator.hasNext()) {
iterator.remove();
}
}
}
In the example above, calling the remove() method inside the while loop will throw
an IllegalStateException.
4. ClassCastException
The ClassCastException is thrown when you attempt to cast one object into another object that
is not a member of the class hierarchy. This could be as simple as trying to cast a Long object to
a String object as shown below:
public class Example {
public void incorrectCastExample() {
Long value = 1967L;
String name = (String) value;

Prepared by Eyoas A. Page 82


}
}
5. ArithmeticException
The ArithmeticException occurs when an exceptional arithmetic condition has occurred. For
example, this type of exception often happens when a program attempts to divide by zero, which
was first illustrated in the InvocationTargetException section (above):
return numerator / 0;
Dividing by zero is not a valid mathematical operation, which throws an ArithmeticException in
Java.
6. IllegalArgumentException
The IllegalArgumentException is often used to capture errors when a provided method value
does not meet expectations. To illustrate, consider an example where a date is requested and
cannot be in the future:
public class Example {
public void validDate(LocalDate localDate) throws IllegalArgumentException {
if (localDate.after(LocalDate.now())) {
throw IllegalArgumentException("localDate=" + localDate + " cannot be in the future");
}
}
}
While a future date is a valid value for the date-based object, the business rules for this instance
requires the object to not be in the future.
Error:
Errors are those exceptional conditions that are not checked by compiler at the compile time.
Errors are checked at runtime. An error not forces you to either use try-catch or throws. Error
and their subclasses are represents errors. Error can’t be avoided by programmer, it is
irrecoverable.
e.g. – OutOfMemoryError etc.
How to write an exception handler?
To write a simple exception handler, first enclose the code that might throw an exception within
try block. When an exception occurs in try block, it will be handled by an appropriate exception

Prepared by Eyoas A. Page 83


handler. Exception handler can associate with try block by using catch block or finally block
after it.
Note: catch and finally block both can be attached with single try block. Hierarchy should
be try-catch-finally.
To understand more, let us see the keywords used in exception handling.
 try
 catch
 finally
 throw
 throws
Try And Catch Blocks In Java
try block is used to enclose the code that might throw an exception. It must be followed by
either catch or finally or both blocks.
Syntax of try block with catch block:

try{
//block of statements
}catch(Exception handler class){
}

Syntax of try block with finally block:

try{
//block of statements
} finally {
}

Syntax of try block with catch and finally block:

try{
//block of statements
}catch(Exception handler class){
}finally{
}

catch block:
Catch block is used for exception handler. It is used after try block.

Prepared by Eyoas A. Page 84


Syntax :

try{
//block of statements
}catch(Exception handler class){
}

4.2. Catching Exceptions


Checked exceptions − A checked exception is an exception that is checked (notified) by the
compiler at compilation-time, these are also called as compile time exceptions. These exceptions
cannot simply be ignored, the programmer should take care of (handle) these exceptions.
For example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler
prompts the programmer to handle the exception.
import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo {
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
If you try to compile the above program, you will get the following exceptions.
Output
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught
or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error

Prepared by Eyoas A. Page 85


The finally Block
The finally block follows a try block or a catch block. A finally block of code always executes,
irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no
matter what happens in the protected code.
finally block is mainly used to do clean-up task. It is always executed even when no exception
occur. It will not execute only in case program exits using System.exit() or because of some fatal
error cause program to abort. It is followed by either catch or try block.
Note: A try block can have one or more catch block associated with it, but only one finally
block can be associates with it.
Syntax of finally without catch:

try{
//block of statements
}finally{
}

Syntax of finally with catch:

try{
//block of statements
}catch(){
}finally{
}

Note the following:


A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses whenever a try/catch block is present.
The try block cannot be present without either catch clause or finally clause.
Any code cannot be present in between the try, catch, finally blocks.

Prepared by Eyoas A. Page 86


4.4 Exception Methods
Following is the list of important methods available in the Throwable class
Sr:No. Method & Description

1 public String getMessage()

Returns a detailed message about the exception that has occurred. This message is
initialized in the Throwable constructor.

2 public Throwable getCause()

Returns the cause of the exception as represented by a Throwable object.

3 public String toString()

Returns the name of the class concatenated with the result of getMessage().

4 public void printStackTrace()

Prints the result of toString() along with the stack trace to System.err, the error output
stream.

5 public StackTraceElement [] getStackTrace()

Returns an array containing each element on the stack trace. The element at index 0
represents the top of the call stack, and the last element in the array represents the
method at the bottom of the call stack.

6 public Throwable fillInStackTrace()

Fills the stack trace of this Throwable object with the current stack trace, adding to any
previous information in the stack trace.

4.6. Defining and Throwing Exceptions


The throws keyword
Whenever an exception occurs in a method you need to handle it by wrapping the code that
caused exception within the try-catch block or, you can throw/postpone it using to the calling

Prepared by Eyoas A. Page 87


method using the throws keyword. Then you need to handle the exception at the calling method.
4.7. Errors and Runtime ExceptionsError
errors are exceptions that happen externally to your Java program. One common example of the
error is when the Java virtual machine (JVM) runs out of memory, which will throw
an OutOfMemoryError.
Runtime - runtime exceptions are internal to your application but are not typically recoverable.
For example, an object that is expected to have a value but is actually null. In this case,
a NullPointerException exception would be thrown.

Prepared by Eyoas A. Page 88


Chapter 5: Packages

5.1. Packages

Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.

A Package can be defined as a grouping of related types (classes, interfaces, enumerations, and
annotations ) providing access protection and namespace management.

Some of the existing packages in Java are −

 java.lang − bundles the fundamental classes


 java.io − classes for input, output functions are bundled in this package

Programmers can define their own packages to bundle a group of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, and annotations are related.

Since the package creates a new namespace there won't be any name conflicts with names in
other packages. Using packages, it is easier to provide access control and it is also easier to
locate the related classes.

Creating a Package

While creating a package, you should choose a name for the package and include
a package statement along with that name at the top of every source file that contains the classes,
interfaces, enumerations, and annotation types that you want to include in the package.

The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.

If a package statement is not used then the class, interfaces, enumerations, and annotation types
will be placed in the current default package.

Prepared by Eyoas A. Page 89


To compile the Java programs with package statements, you have to use -d option as shown
below.

javac -d Destination_folder file_name.java

Then a folder with the given package name is created in the specified destination, and the
compiled class files will be placed in that folder.

Example

Let us look at an example that creates a package called animals. It is a good practice to use
names of packages with lower case letters to avoid any conflicts with the names of classes and
interfaces.

Following package example contains interface named animals −

/* File name : Animal.java */

package animals;

interface Animal {

public void eat();

public void travel();

Now, let us implement the above interface in the same package animals −

package animals;

/* File name : MammalInt.java */

public class MammalInt implements Animal {

public void eat() {

Prepared by Eyoas A. Page 90


System.out.println("Mammal eats");

public void travel() {

System.out.println("Mammal travels");

public int noOfLegs() {

return 0;

public static void main(String args[]) {

MammalInt m = new MammalInt();

m.eat();

m.travel();

The import Statement

Import statement in Java is helpful to take a class or all classes visible for a program specified
under a package, with the help of a single statement. It is pretty beneficial as the programmer
do not require to write the entire class definition. Hence, it improves the readability of the
program.

Syntax 1:
import package1[.package2].(*);
 package1: Top-level package
 package2: Subordinate-level package under package1
 *: To import all the classes

Prepared by Eyoas A. Page 91


java Import Statement Methods
Following are three ways to refer an external class or all external classes specified under a
package:

1. Fully-qualified Name in Java


The import statement is optional, and we can use the fully-qualified name of the class to refer
to a class or package in the program. This method tells the compiler that the class is defined
under a particular package, and we want to use that class or classes in our program. Each time
we want to use a data member or member function defined in the class, we need to refer to it
using a fully-qualified name. It increases the code size of our program and hence makes it less
readable. This is the only disadvantage of this method.

A fully-qualified class name in Java contains the package that the class originated from. An
example of this is java.util.ArrayList. The fully-qualified class name can be obtained using the
getName() method.

A program that demonstrates this is given as follows −

public class Demo {


public static void main(String[] argv) throws Exception {
Class c = java.util.ArrayList.class;
String className = c.getName();
System.out.println("The fully-qualified name of the class is: " + className);
}
}

Output
The fully-qualified name of the class is: java.util.ArrayList

Now let us understand the above program.

Prepared by Eyoas A. Page 92


The getName() method is used to get the fully-qualified name of the class c which is stored in
className. Then this is displayed. A code snippet which demonstrates this is as follows −

Class c = java.util.ArrayList.class;
String className = c.getName();
System.out.println("The fully-qualified name of the class is: " + className);

2. Import Statement in Java:


An import statement tells the compiler the path of a class or the entire package. The import in
Java is a keyword that allows the programmer to access packages available in Java. It is used to
import a package, sub-package, a class, an interface or enum in the Java program.
Below is the implementation to illustrate how we can import a class into our program:

ExampleImport.java

import java.util.*; //imports all the classes and interfaces of the util package
public class ExampleImport
{
/* Driver Code */
public static void main(String ar[])
{
System.out.println("Demonstrating use of import statement in Java");
/* Method from java.util.Date class. */
System.out.println(new Date());
}
}

Output:

Demonstrating use of import statement in Java


Tue Jul 20 18:42:43 UTC 2021

Prepared by Eyoas A. Page 93


In the above code, the java.util package is used in the program and it is included using the import
statement at the start of the program.

Java Static Import

The Java static import was introduced in JDK version 1.5. With the help of static import, the
static variables and methods of imported classes can be accessed. We don't need to specify the
class name or object name to access the methods or variables. Using a static import statement
saves time because the programmer isn't required to use the class name or object name again and
again.

Syntax:

Program before using the static import statement

The following program shows the use of the methods of the Math class without using the static
import statement.

ExampleStaticImport.java

import static java.lang.Math.*;


public class ExampleStaticImport

Prepared by Eyoas A. Page 94


{
/* Driver Code */
public static void main(String[] args)
{
ExampleStaticImport obj = new ExampleStaticImport();
obj.calculateData(9);
}
/* Method definition */
void calculateData(int a)
{
double rt = sqrt(a);
System.out.println("Square root of " + a + " = " + round(rt));
System.out.println("Result of 2 * pi = " + 2 * PI);
}
}

Output:

Square root of 9 = 3
Result of 2 * pi = 6.283185307179586

In the above Java code, the Math class is imported using static import. The methods sqrt(),
round() and variable PI of Math class are directly accessed without using the class name.

Advantages of Java Import Statement


There are certain advantages of Java Import Statements as mentioned below:
 Import statements help in reducing the code size and hence save a lot of time.
 It improves the readability of our code.
 It is pretty useful while handling big projects.
 They can be used to combine the functionality of several classes into one.

CLASSPATH and Import

Prepared by Eyoas A. Page 95


The class path environment variable is used to specify the location of the classes and packages.

When we try to import classes and packages other that those that are available with Java
Standard Library.

JVM verifies the current directly for them, if not available it verifies the set of directories
specified in the ‘CLASSPATH’ environment variable.

CLASSPATH is an environment variable (i.e., global variables of the operating system available
to all the processes) needed for the Java compiler and runtime to locate the Java packages/classes
used in a Java program. (Why not call PACKAGEPATH?) This is similar to another
environment variable PATH, which is used by the Command shell to find the executable
programs.
CLASSPATH can be set in one of the following ways:
1. CLASSPATH can be set permanently in the environment: In Windows, choose control
panel ⇒ System ⇒ Advanced ⇒ Environment Variables ⇒ choose "System Variables"
(for all the users) or "User Variables" (only the currently login user) ⇒ choose "Edit"
(if CLASSPATH already exists) or "New" ⇒ Enter "CLASSPATH" as the variable name
⇒ Enter the required directories and JAR files (separated by semicolons) as the value (e.g.,
".;c:\myProject\classes;d:\tomcat\lib\servlet-api.jar"). Take note that you need to include
the current working directory (denoted by '.') in the CLASSPATH.
To check the current setting of the CLASSPATH, issue the following command:

> SET CLASSPATH

NOTE: For Unixes and Mac OS X: Use forward slash '/' as the directory separator and ':'
as the path seperator, e.g., ".:/usr/local/myproject/classes:/usr/local/tomcat/lib/servlet-
api.jar".
2. CLASSPATH can be set temporarily for that particular CMD shell session by issuing the
following command:

3. > SET CLASSPATH=.;c:\myProject\classes;d:\tomcat\lib\servlet-api.jar

4. Instead of using the CLASSPATH environment variable, you can also use the command-
line option -classpath (or -cp) of the javac and java commands, for example,

Prepared by Eyoas A. Page 96


> java –classpath c:\myProject\classes com.abc.project1.subproject2.MyClass3

Package Scope

Package scope, also known as default or package-private scope, is a visibility modifier that
restricts the accessibility of classes, interfaces, and members (variables, methods, constructors)
within a package. When a class or member is declared with package scope, it is accessible only
within the same package and not from other packages.

In Java, if no visibility modifier (such as public, private, or protected) is specified, the default
visibility is package scope. You can achieve package scope by omitting the visibility modifier
when declaring a class or member.

Here's an example to illustrate package scope in Java:

// File: com.example.package1.MyClass.java package com.example.package1;

class MyClass {

void packageScopedMethod() {

System.out.println("This method has package scope.");

}
}
In the above example, MyClass is declared without any visibility modifier, which means it has
package scope. It can be accessed by other classes within the same package
(com.example.package1), but not from classes in other packages.

// File: com.example.package1.AnotherClass.java package com.example.package1;

public class AnotherClass {

public static void main(String[] args) {

Prepared by Eyoas A. Page 97


MyClass myObject = new MyClass();

myObject.packageScopedMethod(); // Accessible within the same package

}
}

In this example, AnotherClass is also in the same package (com.example.package1), so it can


access the packageScopedMethod() of MyClass.

However, if you try to access MyClass or its package-scoped methods from a different package,
you would get a compilation error.

// File: com.example.package2.YetAnotherClass.java
package com.example.package2;

import com.example.package1.MyClass; // Importing MyClass from another package

public class YetAnotherClass {


public static void main(String[] args) {
MyClass myObject = new MyClass();
myObject.packageScopedMethod(); // Compilation error: Method is not visible
}
}

In this case, YetAnotherClass is in a different package (com.example.package2), so it cannot


access packageScopedMethod() of MyClass due to its package scope.

Package scope provides a way to control the visibility and encapsulation of classes and members
within a package, ensuring that they are only accessible by the intended components of the same
package.

Prepared by Eyoas A. Page 98


Prepared by Eyoas A. Page 99

You might also like