Introduction To Object Oriented Programming

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 128

Object Oriented Programming (OOP)

CHAPTER ONE
Introduction to Object Oriented Programming

Friday, February 16, 2024 Object Oriented Programming in Java 1


What is object oriented programming?

OOP represents an attempt to make programs more closely


model the way people think about and deal with the world.

Friday, February 16, 2024 Object Oriented Programming in Java 2


Introduction to OOP
1.1 Types of Programming Paradigm

The programming paradigms which are most widely used and implemented
by various programming languages are:
 Imperative programming
 Object-oriented programming (OOP)
 Functional programming (FP)
 Generic programming (GP)
 Meta-programming (MP)

Friday, February 16, 2024 Object Oriented Programming in Java 3


Introduction to OOP

1. Imperative Programming

A Machine to Model based programming

Imperative programs describe the details of HOW the results are to

be obtained, in terms of the underlying machine model.

Friday, February 16, 2024 Object Oriented Programming in Java 4


Introduction to OOP
2. Object-Orientation Programming
A Programming with data types

The OOP paradigm introduced mechanisms required to obtain modular


software design and reusability compared to universal accessibility of
implementations by imperative programming.

The main part of the object-oriented paradigm is related to the introduction


of classes which cover basic properties of concepts to be implemented.

Friday, February 16, 2024 Object Oriented Programming in Java 5


Introduction to OOP …
Data Abstraction (specifies behaviour)

Encapsulation (controls visibility of names)

Polymorphism (accommodates various implementations)

Inheritance (facilitates code reuse)

Modularity (relates to unit of compilation)

Friday, February 16, 2024 Object Oriented Programming in Java 6


Introduction to OOP …
3. Functional Programming
An Equations; Expression Evaluation
A different type of programming paradigm is functional programming,
where computation is treated as the evaluation of functions based on the
following properties:
Objects are provided only as constants or as expressions on objects.
Functional programming avoids states of objects and mutable data.
Loops therefore have to be replaced by recursion.

Friday, February 16, 2024 Object Oriented Programming in Java 7


Introduction to OOP …
4. Generic Programming
Generic programming denotes (object-oriented) programming methods
based on the mechanism of parametric polymorphism of data structures
and algorithms to obtain orthogonality, while avoiding the performance
drawback of virtual function call costs in C++.
Orthogonality - is an important concept, addressing how a relatively

small number of components can be combined in a relatively small


number of ways to get the desired results.

Friday, February 16, 2024 Object Oriented Programming in Java 8


Introduction to OOP …
5. Meta-Programming
The paradigm of meta-programming can be briefly explained as
writing a computer program that writes or manipulates other programs
or themselves.
For programming tasks which have to be repeated a great number of
times, this paradigm can be used to obtain an efficient implementation

Friday, February 16, 2024 Object Oriented Programming in Java 9


Introduction to OOP …
1.2 Overview of OO principles
1. What are object-oriented (OO) methods?
OO methods provide a set of techniques for
 Analysing
 Decomposing, and
 Modularizing software system architectures
In general, OO methods are characterized by structuring the system
architecture on the basis of its objects and classes of objects rather
than the actions it performs

Friday, February 16, 2024 Object Oriented Programming in Java 10


Introduction to OOP …
2. What are the benefits of OO?
OO enhances key software quality factors of a system and its
constituent components.
3. What is the rationale for using OO?
In general, systems evolve and functionality changes, but objects
and classes tend to remain stable over time.

Friday, February 16, 2024 Object Oriented Programming in Java 11


Introduction to OOP …
1.3 Overview of Java Programming and types of Java program
Java Background History
Java was created in 1991
By James Gosling et al. of Sun Microsystems.
Initially called Oak, in honour of the tree outside Gosling's window, its
name was changed to Java because there was already a language called Oak.
The original motivation for Java
The need for platform independent language that could be embedded in
various consumer electronic products like toasters and refrigerators.

Friday, February 16, 2024 Object Oriented Programming in Java 12


Introduction to OOP …

 One of the first projects developed using Java

● A personal hand-held remote control named Star 7.


 At about the same time, the World Wide Web and the Internet were gaining
popularity.
 Gosling et al. realized that Java could be used for Internet programming.
Types of Java Program:
1. Java Stand Alone Application
2. Java Applets
3. Java Servlets

Friday, February 16, 2024 Object Oriented Programming in Java 13


Introduction to OOP …
1.3.1 Definition of Java Application, Java Applets
Java Applets
Special type of java program that is executed via the Internet
Typically run on a web browser
Not allowed access to the computer on which they are being run for
security reasons
The Applet class
Subclass of the Panel class defined in the AWT

Friday, February 16, 2024 Object Oriented Programming in Java 14


Introduction to OOP …
1.3.2 Editing, Compiling and Interpreting
Java Technology: A Development Environment
● As a development environment, Java technology provides you with a large suite
of tools:
 A compiler
 An interpreter
 A documentation generator
 A class file packaging tool and so on...

Friday, February 16, 2024 Object Oriented Programming in Java 15


Chapter One Review Questions

1. What is the difference between top-down and bottom-up


programming approaches?
2. Discuss the characteristics of object-oriented paradigm?
3. Java is platform independent. What does it mean?
4. Explain the types of Java program?
5. Discuss the phases of Java programming?

Friday, February 16, 2024 Object Oriented Programming in Java 16


End of Chapter One

Friday, February 16, 2024 Object Oriented Programming in Java 17


Chapter Two

Objects and Classes

Friday, February 16, 2024 Object Oriented Programming in Java 18


Objects and Classes
Java is an Object-Oriented Language. As a language that has the
Object-Oriented feature, Java supports the following fundamental
concepts:
Polymorphism
Inheritance
Encapsulation
Abstraction
Classes
Objects
Instance
Method
Message Passing etc…

Friday, February 16, 2024 Object Oriented Programming in Java 19


Objects and Classes
Programming objects are designed to mimic real-world objects
 For example: Television set / DVD
Objects have two important characteristics
 State: Current data about the object
 For example: A dog has a name, color, etc…

 Behavior: Things the object can do


 For example: A dog can bark, fetch, sit, etc..,

The text boxes and buttons with which you are familiar are programming objects
Objects have both data and methods
Objects of the same class have the same data elements and methods
Objects send and receive messages to invoke actions
The real world can be accurately described as a collection of objects that interact

Friday, February 16, 2024 Object Oriented Programming in Java 20


Class
A class is a template or building block for an object
 We say that an object is an instance of a class
 Classes are the standard unit of programming
 A class is like a blueprint – reusable again and again
 Objects are instantiated (created) from the class
We create several bicycles from the same template
2.1. Defining a class
To define a class the class keyword is followed by the name of the new type. For
example:
class ClassTypeName {
/*class body goes here*/}
This introduces a new class type, although the class body consists only of a comment (the
stars and slashes and what is inside, which will be discussed later in this chapter)

Friday, February 16, 2024 Object Oriented Programming in Java 21


2.2. Creating an Object
To create an object of that class type use the new keyword as follows:
ClassTypeName obj = new ClassTypeName();
But you cannot tell it to do much of anything (that is, you cannot send it
any interesting messages) until you define some methods for it.
Activity 2.1
Define a class called Mammal?
Create an object from the class you define above?

Friday, February 16, 2024 Object Oriented Programming in Java 22


2.3. Instantiating and Using Objects
2.3.1. Printing to the Console
Printing to the console refers to writing the output of a Java program to the
console.
The methods used for streaming output are defined in the PrintStream class.
The methods used for writingconsole output are print(), println() and write().
The print() and println() methods are widely used to direct the output to the
console.
Both these methods are used with the help of the System.outstream.

Friday, February 16, 2024 Object Oriented Programming in Java 23


2.3. Instantiating and Using Objects
2.3.2. Methods and Messages
In many languages (like C and C++), the term function is used to describe a
named subroutine.
The term that is more commonly used in Java is method, as in “a way to do
something.”
Methods in Java determine the messages an object can receive.
Messages are the means by which objects interact.
Sending a message to an object means asking the object to execute or invoke
one of its methods.
This is only possible, if the method is actually known to the object.
The fundamental parts of a method are the name, the arguments,
the return type, and the body. Here is the basic form:
ReturnType methodName( /* Argument list */ )
{/* Method body */}
Friday, February 16, 2024 Object Oriented Programming in Java 24
2.3. Instantiating and Using Objects
2.3.3. Parameter Passing
The return type describes the value that comes back from the method after you
call it.
The argument list gives the types and names for the information that you
want to pass into the method.
The method name and argument list (which is called the signature of the
method)uniquely identify that method.
A method can be called only for an object, and that object must be able to
perform that method call.
If you try to call the wrong method for an object, you’ll get an error message at
compile time.
You call a method for an object by naming the object followed by a period (dot),
followed by the name of the method and its argument list, like this:
objectName.methodName(arg1, arg2, arg3)

Friday, February 16, 2024 Object Oriented Programming in Java 25


2.3. Instantiating and Using Objects

For example, suppose you have a method display( ) that takes no arguments
and returns a value of type int.
Then, if you have an object called obj for which display( ) can be called, you
can say this: int x = obj.display();
The type of the return value must be compatible with the type of x.
This act of calling a method is commonly referred to as sending a message to
an object.
In the preceding example, the message is display() and the object is obj.
Object oriented programming is often summarized as simply “sending
messages to objects.”

Friday, February 16, 2024 Object Oriented Programming in Java 26


2.3. Instantiating and Using Objects
2.3.4. Comparing and Identifying Objects
Comparing objects is an essential feature of OOP languages.
Let's begin with the ==and != operators that can tell if two Java objects are
the same or not, respectively.
For primitive types, being the same means having equal values. If two
integers have different values, the == operator would return false, while the !
= operator would return true.
Integer a = new Integer(1);
Integer b = new Integer(1);
a == b is false
Because by comparing two objects, the value of those objects is not 1.
Rather it is their memory addresses in the stack that are different since both
objects were created using the new operator.
Friday, February 16, 2024 Object Oriented Programming in Java 27
2.3. Instantiating and Using Objects
If we had assigned a to b then we would've had a different result:
Integer a = new Integer(1);
Integer b = a;
a == b is true
Now, let's see what happens when we're using the Integer valueOf method:
Integer a = Integer.valueOf(1);
Integer b = Integer.valueOf(1);
a == b is true
In this case, they are considered the same. This is because the valueOf()
method stores the Integer in a cache to avoid creating too many wrapper
objects with the same value.

Friday, February 16, 2024 Object Oriented Programming in Java 28


2.3. Instantiating and Using Objects
Comparing using equals() method:
 Integer a = new Integer(1);
Integer b = new Integer(1);
a.equals(b) is true

Friday, February 16, 2024 Object Oriented Programming in Java 29


2.3. Instantiating and Using Objects
2.3.5. Destroying Objects
One critical issue when working with objects is the way they are created and
destroyed.
Each object requires resources, most notably memory, in order to exist.
When an object is no longer needed it must be cleaned up or destroyed so
that these resources are released for reuse.
Java uses dynamic memory allocation, exclusively.
Every time you want to create an object, you use the new operator to build a
dynamic instance of that object.
Java provides a feature called a garbage collector that automatically
discovers when an object is no longer in use and destroys it.
The garbage collector “knows” when an object is no longer in use, and it
then automatically releases the memory for that object.

Friday, February 16, 2024 Object Oriented Programming in Java 30


2.3. Instantiating and Using Objects
2.3.6. Enumerated Types
Enumerated types are a common enough need that C, C++, and a number of
other languages have always had them.
Java has enum, too, and it’s much more full-featured than what you find in
C/C++. Here’s a simple example: public enum Spiciness { NOT, MILD,
MEDIUM, HOT, FLAMING
}
This creates an enumerated type called Spiciness with five named values.
Because the instancesof enumerated types are constants, they are in all
capital letters by convention (if there are multiple words in a name, they are
separated by underscores).

Friday, February 16, 2024 Object Oriented Programming in Java 31


2.3. Instantiating and Using Objects
To use an enum, you create are ference of that type and assign it
to an instance:
public class SimpleEnumUse
{
public static void main(String[ ] args)
{Spiciness howHot = Spiciness.MEDIUM;
System.out.println(howHot);
}
}

Friday, February 16, 2024 Object Oriented Programming in Java 32


2.3. Instantiating and Using Objects
The compiler automatically adds useful features when you create an enum.
For example, it creates a toString() so that you can easily display the name of
an enum instance, which is how the print statement above produced its
output.
The compiler also creates an ordinal() method to indicate the declaration
order of a particular enum constant, and a static values() method that
produces an array of values of the enum constants in the order that they were
declared:
public class EnumOrder
{ public static void main(String[] args)
{
for(Spiciness s : Spiciness.values())
System.out.println(s + ", ordinal " + s.ordinal());}}

Friday, February 16, 2024 Object Oriented Programming in Java 33


2.4. Instance Fields
When you define a class, you can put two types of elements in your class:
fields (sometimes called data members), and
methods (sometimes called member functions).

Here is an example of a class with some fields:


class DataOnly {
int i;
double d;
boolean b;
}

You can create an object like this:


DataOnly data = new DataOnly();
Friday, February 16, 2024 Object Oriented Programming in Java 34
2.4. Instance Fields
You can assign values to the fields, but you must first know how to refer to a
member of an object.
This is accomplished by stating the name of the object reference, followed by a
period(dot), followed by the name of the member inside the object:
objectReference.member
For example:
data.i = 47;
data.d = 1.1;
data.b = false;
It is also possible that your object might contain other objects that contain data
you’d like to modify. For this, you just keep “connecting the dots.”
For example: myPlane.leftTank.capacity = 100;
When a primitive data type is a member of a class, it is guaranteed to get a default
value if you do not initialize it: for example the default value of int is 0.

Friday, February 16, 2024 Object Oriented Programming in Java 35


2.4. Instance Fields
It’s best to always explicitly initialize your variables. The DataOnly class
cannot do much of anything except hold data, because it has no methods.

To understand how those work, you must first understand arguments and
return values. A class can contain any of the following variable types:

Local variables: Variables defined inside methods, constructors or blocks


are called local variables.

The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.

.
Friday, February 16, 2024 Object Oriented Programming in Java 36
2.4. Instance Fields
Instance variables: Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated.

Instance variables can be accessed from inside any method, constructor or blocks
of that particular class.
Class variables: Class variables are variables declared within a class, outside any
method, with the static keyword
Activity 2.2
What are the methods used to print result to console?
What are messages?
How to destroy objects?

.
Friday, February 16, 2024 Object Oriented Programming in Java 37
2.5. Constructors and Methods
A constructor initializes an object when it is created.
It has the same name as its class and is syntactically similar to a method.
However, constructors have no explicit return type.
All classes have constructors, whether you define one or not, because Java
automatically provides a default constructor that initializes all member
variables to zero.
However, once you define your own constructor, the default constructor is
no longer used. A class can have more than one constructor.

Friday, February 16, 2024 Object Oriented Programming in Java 38


2.5. Constructors and Methods
Java allows two types of constructors namely:
No argument Constructors
Parameterized Constructors
As the name specifies the no argument constructors of Java does not
accept any parameters instead, using these constructors the instance
variables of a method will be initialized with fixed values for all objects.
Example Parameterized Constructors
public class MyClass {
int num ;
MyClass() {
num =100;
}
}
Friday, February 16, 2024 Object Oriented Programming in Java 39
2.5. Constructors and Methods
Parameterized Constructors Most often, you will need a constructor that
accepts one or more parameters.
Parameters are added to a constructor in the same way that they are added
to a method, just declare them inside the parentheses after the constructor's
name.
Example:
public class MyClass {
int x ;
MyClass(int i )
{
x=i;
}
}
Friday, February 16, 2024 Object Oriented Programming in Java 40
2.5. Constructors and Methods
The static keyword

If you want to have only a single piece of storage for a particular field or

if you need a method that isn’t associated with any particular object of this class. You
can achieve both of these effects with the static keyword.

When you say something is static, it means that particular field or method is not tied
to any particular object instance of that class.

To make a field or method static, you simply place the keyword before the definition.

For example, the following produces a static field and initializes it:

class StaticTest {static int i = 47;}

Friday, February 16, 2024 Object Oriented Programming in Java 41


2.6. Access Modifiers

The Java access modifiers are: public, protected, and private


Public: members are globally accessible and available to other assemblies
(components)
 Globally available within the component too
 Note that Intellisense technology will display exposed members
 For example: Members of the .NET Framework class library are
public

Friday, February 16, 2024 Object Oriented Programming in Java 42


2.6. Access Modifiers
Private: members are part of the implementation
 They are exposed only to the class containing the declaration
 Private members are not visible to other components
 Private members are not visible to other classes

Friday, February 16, 2024 Object Oriented Programming in Java 43


2.6. Access Modifiers
Protected: members can only be accessed from their own package

Friday, February 16, 2024 Object Oriented Programming in Java 44


2.7. Encapsulation
Encapsulation:
The process of binding both attributes and methods together within a class.
Through encapsulation, the internal details of a class can be hidden from
outside.
Data hiding: typically, a class is designed such that its data can be accessed
only by its class methods and insulated from direct outside access. This
process of insulating an object’s data is called data hiding
To achieve encapsulation in Java declare the variables of a class as private
and Provide public setter and getter methods to modify and view the
variables values.
Following is an example that demonstrates how to achieve Encapsulation in
Java:

Friday, February 16, 2024 Object Oriented Programming in Java 45


2.7. Encapsulation
public class EncapTest {
private String name; public void setName(String
private String idNum; newName){
private int age; Name = newName ;
public int getAge (){ }
public void setIdNum (String
return age; }
newId) {
public String getName (){ idNum = newId;}
return name ; }
public String getIdNum (){ }
return idNum;}
public void setAge(int newAge ){
Age = newAge;}

Friday, February 16, 2024 Object Oriented Programming in Java 46


Activity 2.3
 Explain the types of Java constructors?
Explain the types of Java access modifiers?
Explain the concept of encapsulation?

Friday, February 16, 2024 Object Oriented Programming in Java 47


Chapter Two Review Questions
1) Define a sample class with its member data and methods?

2) Show the three types of variable in the defined class?

3) Create a constructor in the defined class?

4) Which Java access modifier is related to inheritance and how it works?

5) What mean by data hiding?

Friday, February 16, 2024 Object Oriented Programming in Java 48


End of Chapter Two

Friday, February 16, 2024 Object Oriented Programming in Java 49


Chapter Three:

Inheritance and Polymorphism

Friday, February 16, 2024 Object Oriented Programming in Java 50


3.1. Inheritance
 Inheritance is the mechanism that permits new class to be created
from existing classes.
 The existing classes are called the base classes /parent classes/
super-classes, and
 The new classes are called the derived classes /child classes/sub-
classes.
 The sub-class can inherit or derive the attributes and methods of
the super-class (es) provided that the super-class allows so.
 Besides, the subclass may add its own attributes and methods.
 Inheritance defines an “is-a” relationship.

Friday, February 16, 2024 Object Oriented Programming in Java 51


3.1. Inheritance
 Example from a class mammal, a number of classes can be derived
such as Human, Cat, Dog, Cow, etc.
 Humans, Cats, Dogs, and Cows all have the distinct characteristics of
mammals.
 In addition, each has its own particular characteristics. It can be said
that a cat “is-a” mammal.
 With inheritance, you can save time during program development
by basing new classes on existing proven and debugged high-quality
software.
 This also increases the likelihood that a system will be implemented
and maintained effectively.

Friday, February 16, 2024 Object Oriented Programming in Java 52


3.1. Inheritance
Syntax
public class (subclass-name) extends (existing-class-name) {
// Changes and additions.
}
extends is the keyword used to inherit the properties of a class.
With the use of the extends keyword, the subclasses will be able to inherit
all the properties of the superclass except for the private properties of the
superclass.
Following is an example demonstrating Java inheritance.
In this example, you can observe two classes namely Calculation and
My_Calculation.
Using extends keyword, the My_Calculation inherits the methods addition
() and Subtraction() of Calculation class.

Friday, February 16, 2024 Object Oriented Programming in Java 53


3.1. Inheritance
class Calculation {
int z;
public void addition (int x ,int y )
{
z=x+y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction (int x ,int y )
{
z = x- y ;
System.out.println("The difference between the given numbers:"+z);
}
}
Friday, February 16, 2024 Object Oriented Programming in Java 54
3.1. Inheritance
public class My_Calculation extends Calculation {
public void multiplication (int x , int y ){
z=x*y;
System.out.println("The product of the given numbers:"+z);
}
public static void main (String args [])
{
int a =20, b =10;
My_Calculation demo =new My_Calculation();
demo.addition(a,b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
} }Friday, February 16, 2024 Object Oriented Programming in Java 55
3.1. Inheritance
In the given program, when an object to My_Calculation class is
created, a copy of the contents of the superclass is made within it.
That is why, using the object of the subclass you can access the
members of a superclass.
A subclass inherits all the members from its superclass.
Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked from
the subclass.
The Superclass reference variable can hold the subclass object, but
using that variable you can access only the members of the superclass.
So, to access the members of both classes it is recommended to always
create reference variable to the subclass.

Friday, February 16, 2024 Object Oriented Programming in Java 56


3.1. Inheritance
Example:
Calculation demo = new My_Calculation();
demo.addition(a,b);
demo.Subtraction(a,b);

Types of Inheritance
Single Inheritance: a subclass derives from a single super-class

Friday, February 16, 2024 Object Oriented Programming in Java 57


3.1. Inheritance
Multiple Inheritance: a subclass derives from more than one super –class

Friday, February 16, 2024 Object Oriented Programming in Java 58


3.1. Inheritance
Multilevel Inheritance: a subclass derives from a super -class which in turn is
derived from another class and so on.

Hierarchical Inheritance: a class has a number of subclasses each of which


may have subsequent subclasses, continuing for a number of levels, so as to
form a tree structure.

Friday, February 16, 2024 Object Oriented Programming in Java 59


3.1. Inheritance

A very important fact to remember is that Java does not support multiple
inheritance. Therefore following example is illegal:

public class extends Animal, Mammal{} is illegal

However, a class can implement one or more interfaces, which has helped
Java get rid of the impossibility of multiple inheritance.

Friday, February 16, 2024 Object Oriented Programming in Java 60


3.1. Inheritance
Activity 3.1

1.What mean by inheritance in programming?


2.What are the advantages of inheritance?
3.Explain the types of inheritance?

Friday, February 16, 2024 Object Oriented Programming in Java 61


3.2. Casting
In Java, type casting is a method or process that converts a data type into
another data type in both ways Narrowing Casting (manually) and
Widening Casting (automatically).
The automatic conversion is done by the compiler and manual conversion
performed by the programmer.
Widening Casting (automatically): converting a smaller type to a larger type
size.
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 intType = 4;
double doubleType = intType; // Automatic casting: int to double
System.out.println(intType); // Outputs 4
System.out.println(doubleType); // Outputs 4.0
} } Friday, February 16, 2024 Object Oriented Programming in Java 62
3.2. Casting
Narrowing Casting (manually):
Converting a larger type to a smaller size type. 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 doubleType = 4.23d;
int intType = (int) doubleType; // Manual casting: double to int
System.out.println(doubleType); // Outputs 4.23
System.out.println(intType); // Outputs 4
}
}

Friday, February 16, 2024 Object Oriented Programming in Java 63


3.3. Method Overriding and Overloading
Overriding:
In object-oriented terms, overriding means to override the functionality of
an existing method.
The benefit of overriding is:
Ability to define a behavior that's specific to the subclass type, which
means a subclass can implement a parent class method based on its
requirement.

Friday, February 16, 2024 Object Oriented Programming in Java 64


3.3. Method Overriding and Overloading
Rules for Method Overriding
 The argument list should be exactly the same as that of the overridden
method.
The return type should be the same as the return type declared in the
original overridden method in the superclass.
The access level cannot be more restrictive than the overridden method's
access level.
For example: If the superclass method is declared public then the overriding
method in the subclass cannot be either private or protected.
Instance methods can be overridden only if they are inherited by the
subclass.
A method declared final cannot be overridden.
Constructors cannot be overridden.

Friday, February 16, 2024 Object Oriented Programming in Java 65


3.3. Method Overriding and Overloading
Overloading
Overloading: Circle and Square have similar calculateArea() method in
their class definition.
Although both methods have the same method name, they have different
method implementation, since the formula for calculating area of each is not
the same.
The ability to use the same name for two or more methods in a class is
known as operation overloading in object-oriented terms.
Methods having the same method signature may pose problems in the
compilation process depending on where they are used in the program.

Friday, February 16, 2024 Object Oriented Programming in Java 66


3.3. Method Overriding and Overloading
Two methods are said to have the same method signature if the name of the
methods are the same; and the number and type of formal parameters are the
same.
In the code fragment below, method A() is overloaded by A(int x), A(int x, int
y), and A(Strings).
These four methods are distinguished in the compilation process by the
number and type of parameters present in the method call.
class A { ... A() { ... } A(int x) { ... } A(int x, int y) { ... } A(String x) { ... } ...
}
The return type of a method does not distinguish overloaded methods from
one another.
However, declaring methods of the same signature in different classes are
considered as valid in object-oriented programming.

Friday, February 16, 2024 Object Oriented Programming in Java 67


3.3. Method Overriding and Overloading
Activity 3.2
1.Show an example casting ?
2.What mean by overriding?
3.Explain method overloading?

Friday, February 16, 2024 Object Oriented Programming in Java 68


3.4. Polymorphism
Polymorphism is a Greek word that means the ability to take multiple forms.
In object-oriented paradigm, polymorphism implies using operation in
different ways, depending upon the instances they are operating upon.
Polymorphism enables you to “program in the general” rather than
“program in the specific.”
In particular, polymorphism enables you to write programs that process
objects that share the same superclass.
The most common use polymorphism in OOP occurs when a parent class
reference is used to refer to a child class object.
Any Java object that can pass more than one IS-A test is considered to be
polymorphic

Friday, February 16, 2024 Object Oriented Programming in Java 69


3.4. Polymorphism
Example 1:
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
Now, the Deer class is considered to be polymorphic since this has multiple
inheritance.
Following are true for the above example:
A Deer IS-A Animal
A Deer IS-A Vegetarian
A Deer IS-A Deer
A Deer IS-A Object

Friday, February 16, 2024 Object Oriented Programming in Java 70


3.4. Polymorphism
When we apply the reference variable facts to a Deer object reference, the
following declarations are legal:
Deer d = new Deer();
Animal a = d;
Vegetarian v =d;
Object o =d;
All the reference variables d, a, v, o refer to the same Deer object

Friday, February 16, 2024 Object Oriented Programming in Java 71


3.4. Polymorphism
Example 2 If class Rectangle is derived from class Quadrilateral, then a
Rectangle object is a more specific version of a Quadrilateral.
Any operation (e.g., calculating the perimeter or the area) that can be
performed on a Quadrilateral can also be performed on a Rectangle.
These operations can also be performed on other Quadrilaterals, such as
Squares, Parallelograms and Trapezoids.
The polymorphism occurs when a program invokes a method through a
superclass Quadrilateral variable at execution time, the correct subclass
version of the method is called, based on the type of the reference stored in
the superclass variable.
Polymorphism enables you to deal in generalities and let the execution-time
environment handle the specifics.

Friday, February 16, 2024 Object Oriented Programming in Java 72


3.4. Polymorphism
Polymorphism promotes extensibility:
Software that invokes polymorphic behavior is independent of the object
types to which messages are sent.
New object types that can respond to existing method calls can be
incorporated into a system without modifying the base system.
Polymorphism also increases code readability since the same message is
used to call different objects to perform the appropriate behavior.

Friday, February 16, 2024 Object Oriented Programming in Java 73


3.5. Super
The super keyword is similar to this keyword. Following are the scenarios
where the super keyword is used.
It is used to differentiate the members of superclass from the members of
subclass, if they have same names.
It is used to invoke the superclass constructor from subclass.
If a class is inheriting the properties of another class. And
if the members of the superclass have the names same as the sub class, to
differentiate these variables we use super keyword as shown below.
super.variable;
super.method();

Friday, February 16, 2024 Object Oriented Programming in Java 74


3.5. Super…
In the given program, you have two classes namely Sub_class and
Super_class, both have a method named display() with different
implementations, and a variable named num with different values.
We are invoking display() method of both classes and printing the value of the
variable num of both classes

Friday, February 16, 2024 Object Oriented Programming in Java 75


3.5. Super…
Here you can observe that we have used super keyword to differentiate the
members of superclass from subclass.
class Super_class {
int num = 20;
//display method of superclass
public void display () {
System.out.println("This is the display method of superclass"); }
}

Friday, February 16, 2024 Object Oriented Programming in Java 76


3.5. Super…
public class Sub_class extends Super_class{
int num =10;
//display method of sub class
public void display () {
System.out.println("This is the display method of subclass");
}
public void my_method (){
//Instantiating subclass
Sub_class sub= new Sub_class();
//Invoking the display() method of sub class
sub.display();
//Invoking the display() method of superclass
super.display();

Friday, February 16, 2024 Object Oriented Programming in Java 77


3.5. Super…
//printing the value of variable num of subclass
System.out.println("value of the variable named num in sub class:”+ sub.num);
//printing the value of variable num of superclass
System.out.println("value of the variable named num in super class:”+ super.num)
}
public static void main (String args []) {
Sub_class obj = new Sub_class();
obj.my_method();
}}

Friday, February 16, 2024 Object Oriented Programming in Java 78


3.5. Super…
Invoking Superclass Constructor
If a class is inheriting the properties of another class, the subclass
automatically acquires the default constructor of the superclass.
But if you want to call a parameterized constructor of the superclass, you
need to use the super keyword as shown below.
super(values);
The following program contains a superclass and a subclass, where the
superclass contains a parameterized constructor which accepts an integer
value, and we used the super keyword to invoke the parameterized
constructor of the superclass.

Friday, February 16, 2024 Object Oriented Programming in Java 79


3.5. Super…
class Superclass {
int age ;
Superclass(int age ){
this.age = age;
}
public void getAge() {
System.out.println("The value of the variable named age in super class is: " +age)
}}
public class Subclass extends Superclass {
Subclass(int age ){
Super(age); }
public static void main (String args []) {
Subclass s = new Subclass(24);
s.getAge();}
}
Friday, February 16, 2024 Object Oriented Programming in Java 80
3.6.The Object class
A class that is not explicitly declared to be a subclass of some other class is
automatically made a subclass of the standard class Object.

public class myClass { . . . }is exactly equivalent to

public class myClass extends Object { . . .}

Since every class is a subclass of Object, a variable of type Object can refer
to any object whatsoever, of any type.

Java has several standard data structures that are designed to hold Objects,
but since every object is an instance of class Object, these data structures
can actually hold any object whatsoever.

Friday, February 16, 2024 Object Oriented Programming in Java 81


3.7. Abstract class
You create an abstract class when you want to manipulate a set of classes through
its common interface.

A class containing abstract methods is called an abstract class. If a class contains


one or more abstract methods, the class itself must be qualified as abstract.

An abstract class is one that is not used to construct objects, but only as a basis for
making subclasses.

An abstract class exists only to express the common properties of all its subclasses.

Abstract method is a method that is incomplete; it has only a declaration and no


method body. The body is in subclass of the abstract class.

Syntax: abstract void add( );

Friday, February 16, 2024 Object Oriented Programming in Java 82


3.8. Interfaces
The interface keyword takes the concept of abstractness one step further. The
abstract keyword allows you to create one or more undefined methods in a class.

You provide part of the interface without providing a corresponding


implementation. The implementation is provided by inheritors.

The interface keyword produces a completely abstract class, one that provides no
implementation at all.

It allows the creator to determine method names, argument lists, and return
types, but no method bodies. An interface provides only a form, but no
implementation.

Friday, February 16, 2024 Object Oriented Programming in Java 83


3.8. Interfaces
Thus, any code that uses a particular interface knows what methods might be called
for that interface, and that’s all. So the interface is used to establish a "protocol"
between classes.

However, an interface is more than just an abstract class taken to the extreme, since
it allows you to perform a variation of "multiple inheritance" by creating a class
that can be up cast to more than one base type.

Friday, February 16, 2024 Object Oriented Programming in Java 84


3.9. Using Interfaces
To create an interface, use the interface keyword instead of the class keyword. As with
a class, you can add the public keyword before the interface keyword (but only if that
interface is defined in a file of the same name).

If you leave off the public keyword, you get package access, so the interface is only
usable within the same package. An interface can also contain fields, but these are
implicitly static and final.

To make a class that conforms to a particular interface, use the implements keyword,
which says, "The interface is what it looks like, but now I’m going to say how it
works." Other than that, it looks like inheritance.

Once you have implemented an interface, that implementation becomes an ordinary


class that can be extended in the regular way.

Friday, February 16, 2024 Object Oriented Programming in Java 85


3.9. Using Interfaces
You can choose to explicitly declare the methods in an interface as public, but they
are public even if you don’t say it.

So when you implement an interface, the methods from the interface must be
defined as public.

Otherwise, they would default to package access, and you are reducing the
accessibility of a method during inheritance, which is not allowed by the Java
compiler.

Note that every method in the interface is strictly a declaration, which is the only
thing the compiler allows

Friday, February 16, 2024 Object Oriented Programming in Java 86


3.9. Using Interfaces
public interface Furniture {// Compile-time constant:

int QUANTITY = 5; // static & final// Cannot have method definitions:void setColor(); //
Automatically public

public class Sofa implements Furniture {

@Override public void setColor(){

System.out.println("Blue"); }

public void getColor() {this.setColor(); }}

public class Table extends Sofa implements Furniture {

@Override public void setColor() {System.out.println("Brown"); }}

Friday, February 16, 2024 Object Oriented Programming in Java 87


3.9. Using Interfaces
Furniture and the class Table extends the class Sofa and implements the interface Furniture.
Here there is multiple inheritance in the class Table.

Sofa obj=new Sofa();

Table obj2=new Table();

obj.getColor(); //returns Blue

obj2.getColor(); //returns Brown

Activity 3.3
Explain polymorphism?
What are abstract classes?
Explain interface and its uses?

Friday, February 16, 2024 Object Oriented Programming in Java 88


Chapter Three Review Questions

1. Discuss inheritance with real world example?

2.Discuss polymorphism with real world example?

3.Explain the use of super keyword?

4.Explain what Object class is?

5.How multiple inheritance achieved in Java show with example

Friday, February 16, 2024 Object Oriented Programming in Java 89


Chapter Four:
Exception Handling

Friday, February 16, 2024 Object Oriented Programming in Java 90


4.1 Exceptions Overview
An exception 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
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
runout 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.
The goals for exception handling in Java are to simplify the creation of large, reliable
programs, and to do so with more confidence that your application doesn’t have an unhandled
error.

Friday, February 16, 2024 Object Oriented Programming in Java 91


4.1 Exceptions Overview
Categories of 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.
Compile-time errors occur when there are syntactical issues present in application
code
For example, missing semicolons or parentheses, misspelled keywords or usage of
undeclared variables.
These syntax errors are detected by the Java compiler at compile-time and an
error message is displayed on the screen.
The compiler prevents the code from being executed until the error is fixed.
Therefore, these errors must be addressed by debugging before the program can be
successfully run.

Friday, February 16, 2024 Object Oriented Programming in Java 92


4.1 Exceptions Overview
For example: if you use File Reader file 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.
Example:
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);
}}
In the above program if the file specified is not found then it will be
generateFileNotFoundException
Friday, February 16, 2024 Object Oriented Programming in Java 93
4.1 Exceptions Overview
Unchecked exceptions:
An unchecked exception is an exception that occurs at the time of execution. These
are also called as Runtime Exceptions.
These include programming bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.
For example: if you have declared an array of size 5 in your program, and trying to
call the 6 element of the array then an
ArrayIndexOutOfBoundsException exception occurs.
Example:
public class Unchecked_Demo {
public static void main (String args []) {
int num [ ] = {1,2,3, 4};
System.out.println(num[5]);}}
If you compile and execute the above program, you will get
ArrayIndexOutOfBoundsException
Friday, February 16, 2024 Object Oriented Programming in Java 94
4.1 Exceptions Overview
Activity 4.1
1.What mean by exception in programming?
2.What are checked and unchecked exceptions explain their difference?

Friday, February 16, 2024 Object Oriented Programming in Java 95


4.2. Catching Exceptions
All exception classes are subtypes of the java.lang.Exception class.
The Exception class is a subclass of the Throwable class.
Other than the Exception class there is another subclass called Error
which is derived from the Throwable class.
The Exception class has two main subclasses: IOException class and
RuntimeException Class.
A method catches an exception using a combination of the try and
catch keywords.
A try/catch block is placed around the code that might generate an
exception.
Code within a try/catch block is referred to as protected code, and
the syntax for using try/catch looks like the following:

Friday, February 16, 2024 Object Oriented Programming in Java 96


4.2. Catching Exceptions …
Syntax
try {
// Protected code }
catch (ExceptionName e1) {
// Catch block }

The code which is prone to exceptions is placed in the try block. When an
exception occurs, that exception occurred is handled by catch block associated
with it.

Every try block should be immediately followed either by a catch block or finally
block.

A catch statement involves declaring the type of exception you are trying to
catch. If an exception occurs in protected code, the catch block (or blocks) that
follows the try is checked.
Friday, February 16, 2024 Object Oriented Programming in Java 97
4.2. Catching Exceptions …
If the type of exception that occurred is listed in a catch block, the exception is passed to the
catch block.
Example:
The following is an array declared with 2 elements. Then the code tries to access the 3 of
element of the array which throws an exception.
import java .io.*;
public class ExcepTest {
public static void main (String args []) {
try {
int a [] = new int[2];
System.out.println(“Access element three :" + a [3]); }
catch (ArrayIndexOutOfBoundsException e ){
System.out.println("Exception thrown :" + e ); }
System.out.println("Out of the block");
}
}

Friday, February 16, 2024 Object Oriented Programming in Java 98


4.2. Catching Exceptions …
This will produce the following outputException thrown:
java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like
the following:
Syntax
ry { // Protected code
}
catch (ExceptionType1 e1){ // Catch block
}
catch (ExceptionType2 e2)
{ // Catch block }
catch (ExceptionType3 e3) {
// Catch block }
You can have any number of catch blocks after a single try. If an exception occurs in the protected code, the
exception is thrown to the first catch block in the list.
If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down
to the second catch statement.
This continues until the exception either is caught or falls through all catches.

Friday, February 16, 2024 Object Oriented Programming in Java 99


4.3. The finally Block
A finally block appears at the end of the catch blocks and has the following syntax: Syntax
try {
// Protected code
}
catch (ExceptionType1 e1)
{
// Catch block
}
catch (ExceptionType2 e2) {
// Catch block
}
catch (ExceptionType3 e3) {
// Catch block}
finally {
// The finally block always executes.
}

Friday, February 16, 2024 Object Oriented Programming in Java 100


4.3. The finally Block
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.

Friday, February 16, 2024 Object Oriented Programming in Java 101


4.4. Exception Methods
public String getMessage(): Returns a detailed message about the
exception that has occurred.
public Throwable getCause(): Returns the cause of the exception.
public String toString(): Returns the name of the class concatenated
with the result ofgetMessage().
public void printStackTrace(): Prints the result of toString().
public StackTraceElement [ ] getStackTrace(): Returns an array
containing each element on the stack trace.
public Throwable fillInStackTrace(): Fills the stack trace of this
Throwable object with the current stack trace.
Activity 4.2
Discuss how to catch an exception?
Explain the use of finally block in caching exception?

Friday, February 16, 2024 Object Oriented Programming in Java 102


4.5. Declaring Exceptions
Java’s built in exceptions don’t always provide the information we need.
So, we sometimes need to supplement these exceptions with our own.

A custom exception gives you more control


to provide extra data about the problem and to handle the exception in
your code. You can create your own exceptions in Java which are called
User defined Exceptions.

Apart from the built in exceptions Java provides, exception classes can be
written by the programmer. These can then be thrown like the built in
Java exceptions. Keep the following points in mind when writing
yourown exception classes:
Friday, February 16, 2024 Object Oriented Programming in Java 103
4.5. Declaring Exceptions
All exceptions must be a child of Throwable.
If you want to write a checked exception that is automatically
enforced by the Handle or Declare Rule, you need to extend the
Exception class.
If you want to write a runtime exception, you need to extend the
RuntimeException class.
We can define our own Exception class as below:
class MyException extends Exception {
//for checked exceptions
}
modifier MyException extends RuntimeException {
//for runtime exceptions
}

Friday, February 16, 2024 Object Oriented Programming in Java 104


4.6. Defining and Throwing Exceptions
It is important to understand how to throw exceptions in Java.
This will allow you to create higher quality code where errors
are checked at compile time instead of runtime, and create
custom exceptions that make debugging and recovery easier.
Throwing an exception is as simple as using the "throw"
statement.
You then specify the Exception object you wish to throw.
Every Exception includes a message which is a human
readable error description. It can often be related to problems
with user input, server, backend, etc.
Here is an example that shows how to throw an exception:
throw new Exception("Exception message");

Friday, February 16, 2024 Object Oriented Programming in Java 105


4.6. Defining and Throwing Exceptions
The Throws keyword
If a method does not handle a checked exception, the method must declare
it using the throws keyword.
The throws keyword appears at the end of a method's signature. A method
can declare that it throws more than one exception, in which case the
exceptions are declared in a list separated by commas.
The throws keyword allows the compiler to help you write code that
handles this type of error, but it does not prevent the abnormal termination of
the program.
With the help of the throws keyword, we can provide information to the
caller of the method about the types of exceptions the method might throw.
The caller has to handle the exception using a try-catch block or propagate
the exception.

Friday, February 16, 2024 Object Oriented Programming in Java 106


4.6. Defining and Throwing Exceptions
Example
import java.io.*;
public class className {
public void withdraw (double amount ) throws RemoteException, InsufficientFundsException {
// Method implementation
}
// Remainder of class definition
}
In the example below, we have created a test method to demonstrate throwing
an exception.
The toString() method returns a textual representation of an object, but in this
case the variable is null. Calling a method on a null reference or trying to
access a field of a null reference will trigger a NullPointerException.

Friday, February 16, 2024 Object Oriented Programming in Java 107


4.7. Errors and Runtime Exceptions
Errors: These are not exceptions at all, but problems that arise beyond the
control of the user or the programmer.
Errors are typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an error will arise.
They are also ignored at the time of compilation. Errors are abnormal
conditions that happen in case of severe failures, these are not handled by the
Java programs.
Errors are generated to indicate errors generated by the runtime environment.
Example: JVM is out of memory
A logical error is always the symptom of a bug in application code leading to
incorrect output e.g. subtracting two variables instead of adding them. In case
of a logical error, the program operates incorrectly but does not terminate
abnormally.
Each statement may need to be checked to identify a logical error, which
makes it generally harder to debug than a runtime error
Friday, February 16, 2024 Object Oriented Programming in Java 108
4.7. Errors and Runtime Exceptions
A runtime error in Java is an application error that occurs during the execution
of a program.
A runtime error occurs when a program is syntactically correct but contains an
issue that is only detected during program execution.
These issues cannot be caught at compile time by the Java compiler and are
only detected by the Java Virtual Machine (JVM) when the application is
running.
Runtime errors are a category of exception that contains several more specific
error types. Some of the most common types of runtime errors are:
• IO errors
• Division by zero errors
• Out of range errors
• Undefined object errors, etc.

Friday, February 16, 2024 Object Oriented Programming in Java 109


4.7. Errors and Runtime Exceptions
Runtime errors occur during program execution (the interpretation phase), after
compilation has taken place.
Any code that throws a runtime error is therefore syntactically correct. A
runtime error could potentially be a legitimate issue in code, for example,
incorrectly formatted input data or lack of resources (e.g. insufficient memory
or disk space).
When a runtime error occurs in Java, the compiler specifies the lines of code
where the error is encountered. This information can be used to trace back
where the problem originated.
It is useful to catch runtime exceptions and continue program execution. To
handle a runtime error, the code can be placed within a try catch block and the
error can be caught inside the catch
block.
Runtime Exceptions Example: Division by zero error

Friday, February 16, 2024 Object Oriented Programming in Java 110


4.7. Errors and Runtime Exceptions
Here is an example of a java.lang.ArithmeticException, a type of runtime
exception, thrown due to division by zero:
public class ArithmeticExceptionExample {
public static void main(String[] args) { int a = 10, b = 0;
System.out.println("Result: "+ a/b);
}
}
In this example, an integer a is attempted to be divided by another integer b,
whose value is zero, leading to a java.lang.ArithmeticException:
Here is an example of a java.lang.ArrayIndexOutOfBoundsExceptionthrown
due to an attempt to access an element in an array that is out of bounds:

Friday, February 16, 2024 Object Oriented Programming in Java 111


4.7. Errors and Runtime Exceptions
To illustrate this, the code in the earlier ArithmeticException example can be
updated as follows:
public class ArithmeticExceptionExample {
public static void main(String[] args) { try {
int a = 10, b = 0; System.out.println("Result: " + a/b);
}
catch (ArithmeticException ae) {
System.out.println("Arithmetic Exception: cannot divide by 0");
}
}
}

Friday, February 16, 2024 Object Oriented Programming in Java 112


4.7. Errors and Runtime Exceptions
Surrounding the code in try catch blocks like the above allows the program to
continue execution after the exception is encountered.
Runtime errors can be avoided where possible by paying attention to detail and
making sure all statements in code are mathematically and logically correct.

Activity 4.4

Explain errors by comparing with exceptions?


Explain runtime exceptions with example?

Friday, February 16, 2024 Object Oriented Programming in Java 113


Chapter Five: Packages

Friday, February 16, 2024 Object Oriented Programming in Java 114


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

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.

Package names and directory structure are closely related.

For example if a package name is college.staff.cs, then there are three


directories, college, staff and cs such that cs is present in staff and
staff is present in college

Friday, February 16, 2024 Object Oriented Programming in Java 115


5.1. Packages
Types of Packages: there are two types of packages; User defined and
Built in packages.
1.Built-in Packages: These packages consist of a large number of classes
which are a part of Java API.
Some of the commonly used built-in packages are:
java.lang: Contains language support classes(e.g classed which defines
primitive data types, math operations). This package is automatically
imported.
 java.io: Contains classed for supporting input / output operations.
 java.util: Contains utility classes which implement data structures like
Linked List, Dictionary and support ; for Date / Time operations.
 java.applet: Contains classes for creating Applets.
 java.awt: Contain classes for implementing the components for
graphical user interfaces (like button , menus etc).
 java.net: Contain classes for supporting networking operations.

Friday, February 16, 2024 Object Oriented Programming in Java 116


5.1. Packages
2. User-defined packages
These are the packages that are defined by the user.
First we create a directory myPackage (name should be same as the name
of the package).
Then create the MyClass inside the directory with the first statement
being the package names.
Name of the package must be same as the directory under which this file is saved
package myPackage;
public class MyClass {
public void getName(String name) {
System.out.println(name);
}}
Packages are Java’s way of doing large scale design and organization. They are
used both to categorize and group classes.
Friday, February 16, 2024 Object Oriented Programming in Java 117
5.2. The Import Statement
If a class wants to use another class in the same package, the package
name need not be used. Classes in the same package find each other
without any special syntax.
Example:

A class named Boss is added to the payroll package that already contains
Employee. The Boss can then refer to the Employee class without using
the payroll prefix, as demonstrated by the following Boss class.
package payroll;
public class Boss {
public void payEmployee (Employee e )
{
e.mailCheck(); }
}

Friday, February 16, 2024 Object Oriented Programming in Java 118


5.2. The Import Statement
What happens if the Employee class is not in the payroll package?
The Boss class must then use one of the following techniques for
referring to a class in a different package. The fully qualified name of
the class can be used. For example:
payroll.Employee
The package can be imported using the import keyword and the wild card
(*). For example: import payroll .*;
The class itself can be imported using the import keyword. For example:
import payroll.Employee;
A class file can contain any number of import statements.
The import statements must appear after the package statement and
before the class declaration.

Friday, February 16, 2024 Object Oriented Programming in Java 119


5.3. Static Imports
The static import declaration is analogous to the normal import
declaration.
Where the normal import declaration imports classes from packages,
allowing them to be used without package qualification,
the static import declaration imports static members from classes,
allowing them to be used without class qualification.
The import provides accessibility to classes and interface whereas
static import provides accessibility to static members of the class.

Friday, February 16, 2024 Object Oriented Programming in Java 120


5.3. Static Imports
Exampe:import static
java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
out.println(“Hello Static Import”);//no need of System.out
}}
Activity 5.1
Explain package and its purpose?
Explain the use of import statement?

Friday, February 16, 2024 Object Oriented Programming in Java 121


5.5. Defining Packages
Programmers can define their own packages to bundle 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

Friday, February 16, 2024 Object Oriented Programming in Java 124


5.5. Defining Packages
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 (except
for comments and white space, of course).

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.

Friday, February 16, 2024 Object Oriented Programming in Java 125


5.5. Defining Packages
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:

package animals;

interface Animal{

public void eat ();

public void travel ();

Now a package/
folder with the name animals will be created in the current directory and
the class files will be placed in it.
Friday, February 16, 2024 Object Oriented Programming in Java 126
5.6. Package Scope
The default access has no keyword, but it is commonly referred to
as package access.

It means that all the other classes in the current package have
access to that member, but to all the classes outside of this
package, the member appears to be private.

Package access allows you to group related classes together in a


package so that they can easily interact with each other.

When you put classes together in a package, thus granting mutual


access to their package access members, you “own” the code in that
package

Friday, February 16, 2024 Object Oriented Programming in Java 127


5.6. Package Scope
Give the member package access by leaving off any access
modifier, and put the other classes in the same package. Then
the other classes in that package can access the member.
Activity 5.2
 Explain package and its purpose?

Explain the use of import statement?


Chapter Five Review Questions
1.Explain the types of packages?
2.What is the difference between import and static import statements?
3.What mean by a CLASSPATH?
4.Define a package and show how the import statement works?
5.Explain the scope of a package?

Friday, February 16, 2024 Object Oriented Programming in Java 128


Friday, February 16, 2024 Object Oriented Programming in Java 129
Lab 2
Lab 2: Write a java program to display the employee details using Scanner
class
package employeedetails;
class EmployeeDetails
{
public static void main(String args[]) {
System.out.println("enter name,id,age,salary");
Scanner sc=new Scanner(System.in);
String n=sc.next();
int i=sc.nextInt();
int a=sc.nextInt();
float s=sc.nextFloat();
System.out.println("name is"+n+"id is" +i+"ageis" +a+ "salaryis" +s);
}
}

Friday, February 16, 2024 Object Oriented Programming in Java 130

You might also like