0% found this document useful (0 votes)
6 views47 pages

Java-Unit 2 Inheritance and Polymorphism

The document covers key concepts of Object-Oriented Programming (OOP) in Java, focusing on inheritance, polymorphism, and multithreading. It explains various types of inheritance, method overriding, and the Object class, along with practical examples. Additionally, it discusses compile-time and runtime polymorphism, including method overloading and dynamic method dispatch.

Uploaded by

Hanock Jacob
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)
6 views47 pages

Java-Unit 2 Inheritance and Polymorphism

The document covers key concepts of Object-Oriented Programming (OOP) in Java, focusing on inheritance, polymorphism, and multithreading. It explains various types of inheritance, method overriding, and the Object class, along with practical examples. Additionally, it discusses compile-time and runtime polymorphism, including method overloading and dynamic method dispatch.

Uploaded by

Hanock Jacob
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/ 47

OBJECT ORIENTED PROGRAMMING WITH JAVA

Unit-2
Inheritance and Polymorphism: Inheritance in java, Super and sub class, Overriding, Object
class, Polymorphism, Dynamic binding, Generic programming, Casting objects, Instance of operator,
Abstract class, Interface in java, Package in java, UTIL package.

Multithreading in java: Thread life cycle and methods, Runnable interface, Thread
synchronization, Exception handling with try catch-finally, Collections in java, Introduction to
JavaBeans and Network Programming.

SHWETHA RANI R S 1ST BCA Page 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

INHERITANCE AND POLYMORPHISM

INHERITANCE IN JAVA

INHERITANCE:EXTENDING A CLASS

Creating a new class, reusing the properties of existing ones. The


mechanism of deriving a new class from an old one is called inheritance. The old
class is known as the base class or super class or parent class and the new one is
called the subclass or derived class or child class.
The idea behind inheritance in java is that you can create new class 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
• For Method Overriding(so runtime polymorphism can be achieved)

• For Code Reusability.


The inheritance allows subclasses to inherit all the variables and methods of
their parent classes. Inheritance may take different forms:

1. Single inheritance(only one super class)

2. Multiple inheritance(server super classes)

3. Hierarchical inheritance (one superclass, many subclasses)

4. Multi-level inheritance(derived from a derived class)

Java does not directly implement multiple inheritance. However, this concept
is implemented using a secondary inheritance path in the form of interfaces.

Defining a subclass:
A sub class is defined as:
Class subclassname extends superclassname

variable declaration;
methods declaration;

SHWETHA RANI R S 1ST BCA Page 2


OBJECT ORIENTED PROGRAMMING WITH JAVA

The keyword extends signifies that the properties of the super classname are
extended to the subclassname. (or) 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. The subclass will now contain its own variables
and methods as well those of the superclass.This kind of situation occurs when we
want to add some more properties to an existing class without actually modifying
it.

Types of inheritance in java


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

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.

class Animal
{
void eat()
{
System.out.println("eating...");
}

SHWETHA RANI R S 1ST BCA Page 3


OBJECT ORIENTED PROGRAMMING WITH JAVA

}
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();
}}

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...");
}
SHWETHA RANI R S 1ST BCA Page 4
OBJECT ORIENTED PROGRAMMING WITH JAVA

}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Hierarchical Inheritance
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...");
}
}
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...

SHWETHA RANI R S 1ST BCA Page 5


OBJECT ORIENTED PROGRAMMING WITH JAVA

APPLICATION OF SINGLE INHERITANCE


Class Room
{
int length:
int breadth:
Room (int x , int y)
{
length=x;
breadth= y;
}
int area()
{
return (length* breadth);
}
}
class BedRoom extends Room
{
int height;
BedRoom (int x, int y, int z)
{
super (x, y)
height = z;
}
int volume ()
{
return (length* breadth* height);
}
class InherTest
{
public static void main(String args[])
{
BedRoom rooml= new BedRoom (14,12,10);
int areal room1.area(); //superclass method.
int volumel = room1.volume (): //baseclass method
System.out.println("Areal = "+areal):
System.out.println("volume1 = " + volume1):
}
}
The output of Program is:
Areal 168
Volumel = 1680

The program defines a class room and extends it to another class bedroom. Note
that the class bedroom defines its own data members and methods.The sub class
bedroom now includes three instance variables, namely length, breadth and
height and two methods area and volume.

The constructor in the derived class uses the super keyword to pass values
SHWETHA RANI R S 1ST BCA Page 6
OBJECT ORIENTED PROGRAMMING WITH JAVA

that are required by the base constructor.

bedroomroom1 = new bedroom (14, 12 , 10 );

calls first the bedroom constructor method, which in turn calls the room
constructor method by using the super keyword. Finally the object room1 of the
subclass bedroom calls the method area defines in the super class as well as the
method volume defined in the subclass itself.

Subclass constructor:
A subclass constructor is used to construct the instance variables of both the subclass
and the superclass.The subclass constructor uses the keyword super to invoke the
Constructor method of the superclass.This keyword super is used subject to the
following conditions:

• Super may only be used within a subclass constructor method

• The call to super class constructor must appear as the first statement
within the subclass constructor.

• The parameters in the super call must match the order and type of the
instance variable declared in the super class.

OVERRIDING METHODS:
Defining a method in the subclass that has the same name, same arguments and same return
type as a method in the superclass. When the method is called, the method defined in the subclass is
invoked and executed instead of the one in the superclass.

Usage of Java Method Overriding


• Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
• Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
• There must be an IS-A relationship (inheritance).

(or)
However, there may be occasions when we want an object to respond to the same method but
have different behaviour when that method is called. That means, we should override the method
defined in the super class. This is possible by defining a method in the subclass that has the same name,
same arguments and same return type as a method in the super class. Then, when that method is called,
the method defined in the sub class is invoked and executed instead of the one in the superclass. This
is known as overriding

SHWETHA RANI R S 1ST BCA Page 7


OBJECT ORIENTED PROGRAMMING WITH JAVA

Illustration of method overriding


class Super
{
int x;
Super (int x)
{
this.x = x;
}
void display ( )
{
System.out.println("Super x = " +x);
}
Class Sub extends Super
{
int y;
sub (int x, int y)
{
super (x);
this.y = y;
}
void display ( )
{
System.out.println("Super x = " + x);
System.out.println("Sub y = +y);
}
}
class Override Test
public static void main(String args[])
{
Sub sl=new Sub (100, 200);
sl.display();
}
Output:
Super x = 100
Sub y =200

Object class in Java


Object class is present in java.lang package. The Object class is the parent class of all the classes in java by
default. In other words, it is the top most 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.
All the methods of Object class can be used by all the subclasses and arrays. The Object class provides
different methods to perform different operations on objects.
Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any
other class then it is a direct child class of Object and if extends another class then it is indirectly derived.
Therefore the Object class methods are available to all Java classes. Hence Object class acts as a root of
inheritance hierarchy in any Java Program
Let's take an example, there is getObject() method that returns an object but it can be of

SHWETHA RANI R S 1ST BCA Page 8


OBJECT ORIENTED PROGRAMMING WITH JAVA

any type like Employee, Student etc, we can use Object class reference to refer that object. For example:

Object obj=getObject();

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.

Methods of Object class


The Object class provides many methods. They are as follows:

• toString() Method
• hashCode() Method
• equals(Object obj) Method
• getClass() method
• finalize() method
• clone() method
• wait(), notify() notifyAll() Methods
toString() Method:
It's provide string representation or convert object to string form. you can override toString() method
to get your own String representation of objects.
public String toString()
{
// Can override and give own definition
}

hashCode() Method:
It's generate unique hashcode for each object. The main advantage of saving objects. It's used to
override for user defined objects for better performance like searching.
equals(Object obj) Method:
It's used to compare the two objects dynamically.
getClass() Method:
It's return runtime class object and used to get metadata information as well.
finalize() method:
This method call required to perform garbage collector.
clone() method:
It used to create the copy or clone of object.
wait(), notify() notifyAll() Methods:
These are used in multithreading.

POLYMORPHISM IN JAVA

SHWETHA RANI R S 1ST BCA Page 9


OBJECT ORIENTED PROGRAMMING WITH JAVA

The word polymorphism means having many forms. In simple words, we can define polymorphism
as the ability of a message to be displayed in more than one form.

Polymorphism is the ability of an object to take on many forms. The most common use of
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

Real-life Illustration: Polymorphism

A person at the same time can have different characteristics. Like a man at the same time is a father,
a husband, an employee. So the same person possesses different behavior in different situations. This
is called polymorphism.
Polymorphism is considered one of the important features of Object-Oriented Programming.
Polymorphism allows us to perform a single action in different ways. In other words, polymorphism
allows you to define one interface and have multiple implementations. The word “poly” means many
and “morphs” means forms, So it means many forms.

Types of polymorphism

In Java polymorphism is mainly divided into two types:

• Compile-time Polymorphism
• Runtime Polymorphism

Type 1: Compile-time polymorphism

It is also known as static polymorphism. This type of polymorphism is achieved by function


overloading or operator overloading.

Method Overloading: When there are multiple functions with the same name but different
parameters then these functions are said to be overloaded. Functions can be overloaded by change in
the number of arguments or/and a change in the type of arguments.

SHWETHA RANI R S 1ST BCA Page 10


OBJECT ORIENTED PROGRAMMING WITH JAVA

Example 1
// Java Program for Method overloading
// By using Different Types of Arguments

class Helper {

// Method with 2 integer parameters

static int Multiply(int a, int b)

{
return a * b; // Returns product of integer numbers
}

// Method 2

// With same name but with 2 double parameters

static double Multiply(double a, double b)

{
return a * b; // Returns product of double numbers

}
}

// Class 2
// Main class

class GFG {

public static void main(String[] args) // Main driver method

{
// Calling method by passing

// input as in arguments

System.out.println(Helper.Multiply(2, 4));

System.out.println(Helper.Multiply(5.5, 6.3));
}
}
Output:
8
34.65
Type 2: Runtime polymorphism

SHWETHA RANI R S 1ST BCA Page 11


OBJECT ORIENTED PROGRAMMING WITH JAVA

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden


method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.
Example:
class Shape
{
void draw()
. {
System.out.println("drawing...");}
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle...");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println("drawing circle...");
}
}
class Triangle extends Shape
{
void draw()
{
System.out.println("drawing triangle...");
}
}
class TestPolymorphism2
{
public static void main(String args[])
{
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}

SHWETHA RANI R S 1ST BCA Page 12


OBJECT ORIENTED PROGRAMMING WITH JAVA

Casting objects
Upcasting and Downcasting in Java
A process of converting one data type to another is known
as Typecasting and Upcasting and Downcasting is the type of object typecasting. In Java, the
object can also be typecast like the datatypes. Parent and Child objects are two types of objects.
So, there are two types of typecasting possible for an object, i.e., Parent to Child and Child to
Parent or can say Upcasting and Downcasting.

Typecasting is used to ensure whether variables are correctly processed by a function or not.
In Upcasting and Downcasting, we typecast a child object to a parent object and a parent object
to a child object simultaneously. We can perform Upcasting implicitly or explicitly, but downcasting
cannot be implicitly possible.

1) Upcasting

Upcasting is a type of object typecasting in which a child object is typecasted to a parent class
object. By using the Upcasting, we can easily access the variables and methods of the parent class to
the child class. Here, we don't access all the variables and the method. We access only some specified
variables and methods of the child class. Upcasting is also known as Generalization and Widening.

UpcastingExample.java

class Parent{

void PrintData()

System.out.println("method of parent class");

class Child extends Parent

void PrintData()

System.out.println("method of child class");

}
SHWETHA RANI R S 1ST BCA Page 13
OBJECT ORIENTED PROGRAMMING WITH JAVA

class UpcastingExample

public static void main(String args[])

Parent obj1 = (Parent) new Child();

Parent obj2 = (Parent) new Child();

obj1.PrintData();

obj2.PrintData();

2) Downcasting

Upcasting is another type of object typecasting. In Upcasting, we assign a parent class reference object
to the child class. In Java, we cannot assign a parent class reference object to the child class, but if we
perform downcasting, we will not get any compile-time error. However, when we run it, it throws
the "ClassCastException". Now the point is if downcasting is not possible in Java, then why is it
allowed by the compiler? In Java, some scenarios allow us to perform downcasting. Here, the subclass
object is referred by the parent class.

Below is an example of downcasting in which both the valid and the invalid scenarios are explained:

DowncastingExample.java

//Parent class

class Parent {

String name;

void showMessage()

System.out.println("Parent method is called");


SHWETHA RANI R S 1ST BCA Page 14
OBJECT ORIENTED PROGRAMMING WITH JAVA

class Child extends Parent

int age;

void showMessage()

System.out.println("Child method is called");

public class Downcasting

public static void main(String[] args)

Parent p = new Child();

p.name = "Shubham";

Child c = (Child)p;

c.age = 18;

System.out.println(c.name);

System.out.println(c.age);

c.showMessage();

GENERIC PROGRAMMING

SHWETHA RANI R S 1ST BCA Page 15


OBJECT ORIENTED PROGRAMMING WITH JAVA

The Java Generics programming is introduced to deal with type-safe objects. It makes the code
stable by detecting the bugs at compile time. Before generics, we can store any type of objects in the
collection, i.e., non-generic. Now generics force the java programmer to store a specific type of
objects.

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-
defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to
create classes that work with different data types. An entity such as class, interface, or method that
operates on a parameterized type is a generic entity.
Why Generics?
The Object is the superclass of all other classes, and Object reference can refer to any object. These
features lack type safety. Generics add that type of safety feature. We will discuss that type of safety
feature in later examples
Types of Java Generics

Generic Method: Generic Java method takes a parameter and returns some value after performing a
task. It is exactly like a normal function, however, a generic method has type parameters that are
cited by actual type. This allows the generic method to be used in a more general way. The compiler
takes care of the type of safety which enables programmers to code easily since they do not have to
perform long, individual type castings.
Generic Classes: A generic class is implemented exactly like a non-generic class. The only
difference is that it contains a type parameter section. There can be more than one type of parameter,
separated by a comma. The classes, which accept one or more parameters, are known as
parameterized classes or parameterized types.
Generic Class
Like C++, we use <> to specify parameter types in generic class creation. To create objects of a
generic class, we use the following syntax.
// To create an instance of generic class

BaseType <Type> obj = new BaseType <Type> ()

// Java program to show working of user defined


// Generic classes
// We use < > to specify Parameter type
class Test<T>
{
T obj; // An object of type T is declared

Test(T obj)
{
this.obj = obj; } // constructor

public T getObject()
{
return this.obj;
}
SHWETHA RANI R S 1ST BCA Page 16
OBJECT ORIENTED PROGRAMMING WITH JAVA

class Main // Driver class to test above


{
public static void main(String[] args)

{
Test<Integer> iObj = new Test<Integer>(15); // instance of Integer type

System.out.println(iObj.getObject());

// instance of String type

Test<String> sObj = new Test<String>("BCA");

System.out.println(sObj.getObject());
}}
Output
15
BCA

Instance of operator
The java instanceof operator is used to test whether the object is an instance of the specified
type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with any
variable that has null value, it returns false.
Simple example of java instanceof
Let's see the simple example of instance operator where it tests the current class.
class Simple1
{
public static void main(String args[])
{
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1); //true
}
}

Output:true

ABSTRAT CLASSES:
If the class acts as base class for many other classes and is not useful on its own, then we can
avoid instantiation and only it's declaration is enough. This is achieved by using abstract
keyword. Similarly we can have only method declaration and allow derived class to define it by
using abstract keyword. Such class is called abstract class and such method is called abstract
method. It can have abstract and non-abstract methods (method with the body).

SHWETHA RANI R S 1ST BCA Page 17


OBJECT ORIENTED PROGRAMMING WITH JAVA

We have seen that by making a method final we ensure that the method is not
redefined in a sub class. That is, the method can never be sub classed. Java allows us to
do something that is exactly opposite to this. That is, we can indicate that a method must
always be redefined in a sub class, thus making overriding compulsory. This is done using
the modifier keyword abstract in the method definition.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}
Output:
running safely

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.
When a class contains one or more abstract methods, it should also be declared
Abstract as shown in the example above.

While using abstract classes, we must satisfy the following conditions:

• We cannot use abstract classes to instantiate objects

directly. Eg: bike b =new bike( );

Is illegal because bike is an abstract class.

• The abstract methods of an abstract class must be defined in its subclass.


We cannot declare abstract constructors or abstract static method

INTERFACE IN JAVA

INTERFACES:MULTIPLE INHERITANCE

Java does not support multiple inheritance. That is, classes in Java cannot
have more than one superclass. For instance, a definition like:

SHWETHA RANI R S 1ST BCA Page 18


OBJECT ORIENTED PROGRAMMING WITH JAVA

Class A extends B extends C

.............................

.............................

Is not permitted in Java.a large number of real-life applications require the use of
multiple inheritance where by we inherit methods and properties from several
distinct classes.

Java provides an alternate approach known as interfaces to support the


concept of multiple inheritance.Although a Java class cannot be a subclass of more
than one superclass, it can implement more than one interface, there by enabling
us to create classes that build up-on other classes without the problems created by
multiple inheritance.

DEFININGINTERFACES:

An interface is basically a kind of class. Like classes, interfaces contain


methods and variables but with a major difference. The difference is that interfaces
define only abstract methods and final fields. This means that interfaces do not
specify any code to implement these methods and data fields contain only
constants.

Interface interfacename

variable declaration;

methods declaration;

The syntax for defining an interface is very similar to that for defining a class.
Here, interface is the keyword and interfacename is any valid Java
variable(just like class names).
Note that all variables are declared as constants.
EXTENDINGINTERFACES

Like classes, interfaces can also be extended.That is, an interface can be


sub interfaced from other interfaces. The new subinterface will inherit all the

SHWETHA RANI R S 1ST BCA Page 19


OBJECT ORIENTED PROGRAMMING WITH JAVA

members of the super interface in the manner similar to subclasses.This is achieved


using the keyword extends.

Interface name2 extends name1

Body of name2

For example, we can put all the constants in one interface and the methods in the

Interface ItemConstants

Int code=1001 ;

String name=“Fan”;

Interface Item extends ItemConstants

Void display();

}
other. This will enable us to use the constants in classes where the methods are
not required. Example

IMPLEMENTING INTERFACES
Interfaces are used as "superclasses" whose properties are inherited by classes. It
is therefore necessary to create a class that inherits the given interface. This is
done as follows:
class classname implements interfacename
{
body of classname.
}

Here the class classname "implements" the interface interfacename. A more


general form of implementation may look like this:
class classname extends superclass

SHWETHA RANI R S 1ST BCA Page 20


OBJECT ORIENTED PROGRAMMING WITH JAVA

implements interface1, interface2,…….


{
body of classname
}
This shows that a class can extend another class while implementing interfaces.
Program :Implementing interfaces

interface Area // Interface defined


{
final static float pi = 3,14F;
float compute (float x, float y);
}
class Rectangle implements Area
{
return (x*y);
}
public float compute (float x, float y)
}
class Circle implements Area
{
public float compute (float x, float y)
{
return (pi*x*x);
}
}
class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Circle cir = new Circle();
Area area;
area =rect;
System.out.println("Area of Rectangle =+area.compute(2.5,3.5));
System.out.println ("Area of Circle = "+area.compute(4.5,5.5));
}
}

Implementing Multiple Inheritance


Progam:Implementing multiple inheritance

class Student
{
int rollNumber;
void getNumber(int n)
{
SHWETHA RANI R S 1ST BCA Page 21
OBJECT ORIENTED PROGRAMMING WITH JAVA

rollNumber = n;
}
void putNumber ( )
{
System.out.println (" Roll No : " + rollNumber);
}
}
class Test extends Student
float part1, part2;
void getMarks (float ml, float m2)
part1 = m1;
part2 = m2;
}
void putMarks ( )
{
System.out.println("Marks obtained ");
System.out.println("Part 1 = " + part 1);
System.out.println("Part 2 = " + part 2);
}
}
interface Sports
{
float sportWt = 6.OF;
void putwt ();
}
class Results extends Test implements Sports
{
float total;
public void putWt ( )
{
System.out.println("Sports Wt = " + sportWt);
}
void display ( )
{
total = partl+part2 + sportWt;
put Number();
putMarks();
putWt ();
System.out.println("Total score = " + total);
}
}
class Hybrid
public static void main(String args[])
Results student1 = new Results();
student1.getNumber (1234);
student1.getMarks (27.5F, 33.0F);
student1.display();

SHWETHA RANI R S 1ST BCA Page 22


OBJECT ORIENTED PROGRAMMING WITH JAVA

Output of the Program 10.2:


Roll No : 1234
Marks obtained
Part1 = 27.5
Part2 = 33
Sports Wt = 6
Total score = 66.5

SHWETHA RANI R S 1ST BCA Page 23


OBJECT ORIENTED PROGRAMMING WITH JAVA

JAVA PACKAGES

INTRODUCTION:

Packages are Java’s way of grouping a variety of classes and / or interfaces


together. The grouping is usually done according to functionality. In fact, packages act
as“containers”for classes.

Benefits:

• The classes contained in the packages of other programs can be easily reused.

• In packages, classes can be unique compared with classes in other


packages. That is two classes in two different packages can have the same
name. They may be referred by their fully qualified name, comprising the
package name and the classname.

• Packages provide a way to “hide” classes thus preventing other


programs or packages from accessing classes that are meant for initernal
use only.

• Packages also provide a way for separating “design” from “coding”.


First we can design classes and decide their relationships, and then we can
implement the Java code needed for the methods. It is possible to change
the implementation of any method without affecting the rest of the design.

JAVA API PACKAGES:

Java API provides a large number of classes grouped into different


packages according to functionality.Most of the time we use the packages
available with the Java API. Table below shows the classes that belongs to each
package.

Java

lang util io awt net applet

SHWETHA RANI R S 1ST BCA Page 24


OBJECT ORIENTED PROGRAMMING WITH JAVA

FrequentlyusedAPIpackages

Packagename Contents

java.lang Language support classes. These are classes that Java compiler itself
uses and therefore they are automatically imported.They include
classes for primitive types, strings, math functions, threads
and exceptions.

java.util Language utility classes such as vectors,hash tables,random


numbers,date, etc.,

java.io Input/output support classes.They provide facilities for the input


and output of data.
java.awt Set of classes for implementing Graphical User interface(GUI).
They include classes for windows,buttons, lists,menus and soon.

java.net Classes for networking.They include classes for communicating


with local computers as well as with internet servers.

java.applet Classes for creating and implementing applets.

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");

How to access package from another package?


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

SHWETHA RANI R S 1ST BCA Page 25


OBJECT ORIENTED PROGRAMMING WITH JAVA

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.

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();

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{

SHWETHA RANI R S 1ST BCA Page 26


OBJECT ORIENTED PROGRAMMING WITH JAVA

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();

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.

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();

SHWETHA RANI R S 1ST BCA Page 27


OBJECT ORIENTED PROGRAMMING WITH JAVA

Java.util Package

It contains the collections framework, legacy collection classes, event model, date and time facilities,
internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator,
and a bit array).

The package java.util contains a number of useful classes and interfaces. Although the name of
the package might imply that these are utility classes, they are really more important than that. In
fact, Java depends directly on several of the classes in this package, and many programs will find
these classes indispensable. The classes and interfaces in java.util include:

• The Hashtable class for implementing hashtables, or associative arrays.


• The Vector class, which supports variable-length arrays.
• The Enumeration interface for iterating through a collection of elements.
• The StringTokenizer class for parsing strings into distinct tokens separated by
delimiter characters.
• The EventObject class and the EventListener interface, which form the basis of the
new AWT event model in Java 1.1.
• The Locale class in Java 1.1, which represents a particular locale for
internationalization purposes.
• The Calendar and TimeZone classes in Java. These classes interpret the value of
a Date object in the context of a particular calendar system.
• The ResourceBundle class and its
subclasses, ListResourceBundle and PropertyResourceBundle, which represent sets

SHWETHA RANI R S 1ST BCA Page 28


OBJECT ORIENTED PROGRAMMING WITH JAVA

MULTITHREADING IN JAVA
Multithreading is a conceptual programming paradigm where a program
(process) is divided into two or more subprograms (processes), which can be
implemented at the same time in parallel.

A thread is similar to a program that has a single flow of control. It has a


beginning, a body, and an end and executes commands sequentially. A unique
property of Java is its support for multithreading. That is, Java enables us to use
multiple flows of control in developing programs. Each flow of control may be
thought of as a separate tiny program (or module) known as a thread that runs in
parallel. A program that contains multiple flows of controls known as
multithreaded program.

Multithreading is useful in a number of ways. It enables programmers to


do multiple things at one time. They can divide a long program into threads and
execute them in parallel.Threads are extensively used in Java–enabled browsers
such as HotJava. These browsers can download a file to the local computer, display
a Web page in the window, output another Web page to a printer and so on.

LIFECYCLEOFATHREAD

During the lifetime of a thread, there are many states it can enter.They include:

1. Newborn state

2. Runnable state

3. Running state

4. Blocked state

5. Dead state

SHWETHA RANI R S 1ST BCA Page 29


OBJECT ORIENTED PROGRAMMING WITH JAVA

1. Newborn State:

When we create a thread object, the thread is born and is said to be


in newborn state. The thread is not yet scheduled for running. At
this state, we can do only one of the following things with it.

• Schedule it for running using start( )method.

• Kill it usingstop ()method.

If scheduled, it moves to the running state.If we attempt to use any other


method at this stage, an exception will be thrown.

2.Runnable State:

This runnable state means that the thread is ready for execution and is
waiting for the availability of the processor. That is,the thread has joined
the queue of threads that are waiting for execution. If all threads have equal
priority, then they are given time slots for execution in round robin
fashion. I.e., first-come, first – serve manner.The thread that relinquishes
control joins the queue at the end and again waits for its turn.This process

SHWETHA RANI R S 1ST BCA Page 30


OBJECT ORIENTED PROGRAMMING WITH JAVA

of assigning time to threads is known as time-slicing.

However, if we want a thread to relinquish control to another thread of


equal priority before its turn comes, we can do so by using the yield()
method.

3.Running state:

Running means that the processor has given its time to the thread for
its execution. The thread runs until it relinquishes control on its own or it
is pre-empted by a higher priority thread. A running thread may relinquish
its control in one of the following situations.

1. It has been suspended using suspend ( ) method. A suspended thread


can be revived by using the resume ( ) method. This approach is useful
when we want to suspend thread for sometime duet certain reason, but
do not want to kill it.

2. It has been made to sleep, we can put a thread to sleep for a specified
time period using the method sleep (time) where time is in
milliseconds. This means that the thread is out of the queue during this
time period. The thread re-enters the runnable state as soon as this time
period is elapsed.

3. It has been told to wait until some even to occurs.This is done using the wait()
methods.The thread can be scheduled to run again using the notify() method.

4. Blocked State

A thread is said to be blocked when it is prevented from entering into the


runnable state and subsequently by running state. This happens when the thread is
suspended, sleeping or waiting in order to satisfy certain requirements. A blocked
thread is considered “not runnable ”but not dead and therefore fully qualified to
run again.

5. Dead State

Every thread has life cycle. A running thread ends its life when it has completed
executing its run() method.A thread can be killed as soon it is born, or while it is
running or even when it is in “not runnable”(blocked) conditio

SHWETHA RANI R S 1ST BCA Page 31


OBJECT ORIENTED PROGRAMMING WITH JAVA

Thread methods
Use of yield(),stop(),sleep() methods
class A extends Thread
{
public void run()
{
for (int i =1; i< 5; i++)
{
if(i==1) yield();
System.out.println("\tFrom Thread A : i="+i);
}
System.out.println("exit from A ");
}
}
class B extends Thread
{
public void run ( )
{
for (int j=1; j<=5; j++)
{
System.out.println("\tFrom Thread B: j=”+j);
if (j==3) stop();
System.out.println("Exit from B ");
}
}
class C extends Thread
{
public void run ( )
{
for (int k=1; k<=5; k++)
{
System.out.println("\tFrom Thread C: k = " +k);
if (k==1)
try
{
sleep (1000);
}
catch(Exception e)
{
{
System.out.println("Exit from C ");
}
}
class ThreadMethods
{
public static void main(String args[])
SHWETHA RANI R S 1ST BCA Page 32
OBJECT ORIENTED PROGRAMMING WITH JAVA

{
A threadA= new A( );
B threadB= new B( ); C threadC=new C();
System.out.println("Start thread A");
threadA.start();
System.out.println("Start thread B");
threadB, start();
System.out.println("Start thread C");
threadC.start();
System.out.println("End of main thread");
}
}
IMPLEMENTING THE ‘RUNNABLE’ INTERFACE

We can create threads in two ways:one by using the extended Thread


class and another by implementing the Runnable interface.The Runnable
interface declares the run() method that is required for implementing threads in
our programs.

Steps:

1. Declare the class as implementing the Runnable interface.

2. Implement the run()method.

3. Create a thread by defining an object that is instantiated from


ths“runnable”class as the target of the thread.

4. Call the thread’s start ()method to run the thread.

Program: Using Runnable interface

class X implements Runnable


{
public void run ( )
{
for (int i = 1; i<=10; i++)
{
System.out.println("\tThreadX " +i);
}
System.out.println("End of ThreadX");
}
}
class RunnableTest
{
public static void main(String args[])
{
X runnable = new X();
SHWETHA RANI R S 1ST BCA Page 33
OBJECT ORIENTED PROGRAMMING WITH JAVA

Thread threadX= new Thread ( runnable);


Threadx.start();
System.out.println("End of main Thread");
}
}

THREAD SYNCHRONIZATION

So far, we have seen threads that use their own data and methods provided
inside their run () methods. What happens when they try to use data and methods
outside themselves?On such occasions,they may compete for the same resources
and may lead to serious problems. For example, one thread may try to read a record
from a file while another is still writing to the same file. Depending on the
situation, we may get strange results. Java enables overcome this problem using
technique known as synchronization.

In case of Java, the keyword synchronized helps to solve such problems


by keeping a watch on such locations. For example, the method that will read
information from a file and the method that will update the same fil may be
declared as synchronized. Example:

synchronized void update()

..............................

............................. //code here is synchronized

.............................

When we declare a method synchronized, Java creates a “monitor” and hands it


over to the thread that calls the method first time. As long as the thread holds the
monitor, no other thread can enter the synchronized section of code. A monitor is
like a key and the thread that holds the key can only open the lock.

It is also possible to mark a block of code as synchronized as shown below:

synchronized(lock–object)

..........................

......................... //code here is synchronized

SHWETHA RANI R S 1ST BCA Page 34


OBJECT ORIENTED PROGRAMMING WITH JAVA

Whenever a thread has completed its work of using synchronized method


(or block of code),it will hand over the monitor to the next thread that is ready to
use the same resource.

An interesting situation may occur when two or more threads are waiting
to gain control of a resource. Due to some reason, the condition on which the
waiting threads rely onto gain control does not happen.This results in what is
known as deadlock.

Exception handling with try catch-finally


EXCEPTIONS

An exception is a condition that is caused by a run – time error in the program. When the
Java interpreter encounters an error such as dividing an integer by zero, it creates an
exception object and throws it.

The purpose of exception handling mechanism is to provide a mean to detect and


report an “exceptional circumstances “so that an appropriate action can be taken.
Error handling code that performs the following tasks:

1. Find the problem(Hit the exception)

2. Inform that an error has occurred(Throw the exception)

3. Receive the error information(Catch the exception)

4. Take corrective actions(Handle the exception)

The error handling code basically consists of two segments, one to detect errors and to
Throw exceptions and the other to catch exceptions and to take appropriate actions.

Exception Type Cause of Exception

ArithmeticException Caused by math errors such as division by zero

ArrayIndexOutOfBoundsException Caused by bad array indexes

ArrayStoreException Caused when a program tries to store the wrong type


of data in an array

SHWETHA RANI R S 1ST BCA Page 35


OBJECT ORIENTED PROGRAMMING WITH JAVA

FileNotFoundException Caused by an attempt to access a nonexistent file

IOException Caused by general I/O failures ,such as inability to


read from a file

NullPointerException Cause by referencing a null object

NumberFormatException Caused when a conversion between strings and number


fails

OutOfMemoryException Caused when there is no not enough memory to


allocate a new object

SecurityException Caused when an applet tries to perform an action not


allowed by the browser security setting

StackOverflowException Caused when the system runs out of stack space

StringIndexOutOfBoundsException Caused when a program attempts to access a


nonexistent character position in a string

Try catch block

The basic concepts of exception handling are throwing an exception and catching it.

trybloc
k
Statement that causes
anexception
Exception object creator

Throws exception object

catchBlock

Statement that handles


theexception
Exceptionhandler

SHWETHA RANI R S 1ST BCA Page 36


OBJECT ORIENTED PROGRAMMING WITH JAVA

Exception handling mechanism

Java uses a keyword try to preface a block of code that is likely to cause an
error condition and “throw” an exception. A catch block defined by the keyword
catch “catches” the exception “thrown” by the try block and handles it
appropriately. The catch block is added immediately after the tryblock.

Eg:

....................................

....................................

try

statement; //generates an exception

catch(Exceptiontype e )

statement; //processes the exception

.....................................

.....................................

The try block can have one or more statements that could generate an
exception. If anyone statement generates an exception, the remaining statements
in the block are skipped and execution jumps to the catch block that is placed next
to the tryblock.

The catch block too can have one or more statements that are necessary to
process the exception. Remember that every try statement should be followed by
at least one catch statement; otherwise compilation error will occur.

Program to illustrate using try and catch for exception handling

Program : Using try and catch for exception handling


class Error3

SHWETHA RANI R S 1ST BCA Page 37


OBJECT ORIENTED PROGRAMMING WITH JAVA

{
public static void main(String args[])
int a = 10;
int b = 5;
int c = 5;
int x, y ;
try
{
x = a (b-c); // Exception here
}
catch (ArithmeticException e)
System.out.println("Division by zero");
}
y = a / (b+c);
System.out. println ("y = " + y);
}
}

Output
Division by zero
y =1

MULTIPLECATCHSTATEMENTS

It is possible to have more than one catch statement in th catch block.

................................

................................

try

statement; //generates an exception

catch(Exceptiontype1e)

statement; //processesexceptiontype1

SHWETHA RANI R S 1ST BCA Page 38


OBJECT ORIENTED PROGRAMMING WITH JAVA

catch(Exceptiontype2e)

statement; //processesexceptiontype2

catch(ExceptiontypeN e)

statement; //processes exception type N

When an exception in a try block is generated, the Java treats the multiple catch
statements like cases in a switch statement. The first statement whose parameter
matches with the exception object will be executed, and the remaining statements
will skipped.

NotethatJavadoesnotrequireanyprocessingoftheexceptionatall.Wecansimplyh
aveacatch statement with an empty block to avoid program abortion.

Eg:

catch(Exception e);

The catch statement simply ends with a semicolon, which does nothing. This
statement will catch an exception and then ignore it.
Program:Using multiple catch blocks
class Erro4
{
public static void main(String args[])
{
int a[ ] = {5, 10};
int b = 5;
try
{
int x = a[2] / b - a [1];

SHWETHA RANI R S 1ST BCA Page 39


OBJECT ORIENTED PROGRAMMING WITH JAVA

}
catch (ArithmeticException e)
{
System.out.println (Division by zero");
}
catch (ArraylndexOutOfBounds Exception e)
{
System.out.println("Array index error");
}
catch (ArrayStoreException e)
{
System.out.println ("Wrong data type");
}
int y = a[1] / a[0];
System.out. println ("y = " + y);
}
}
Output:
Array index error
y=2

USING finally STATEMENT

Java supports another statement known as finally statement that can be used to handle an exception that
is not caught by any of the previous catch statements, finally block can be used to handle any exception
generated within a try block. It may be added immediately after the try block or after the last catch block
When a finally block is defined, this is guaranteed to execute, regardless of whether or not an exception is
thrown. As a result, we can use it to closing files and releasing system resources

try
{
…….
…….
}
finally
{
……
}

Or

try
{
….
…..
SHWETHA RANI R S 1ST BCA Page 40
OBJECT ORIENTED PROGRAMMING WITH JAVA

}
catch(…..)
{
…..
}

catch(…..)
{
…..
}
.
.
.
finally
{
…..
}

Try catch finally block

class TestFinally
{
public static void main(String args[]
{
try
{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println(“Finally block is always executed”);
}
System.out.println(“rest of the code”);

}
}
Output:
Finally block is always excecuted

SHWETHA RANI R S 1ST BCA Page 41


OBJECT ORIENTED PROGRAMMING WITH JAVA

Collections in Java
The Collection in Java is a framework that provides an architecture to store and manipulate the group
of objects.

Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many interfaces
(Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet).

Any group of individual objects which are represented as a single unit )illloiooi9l known as the
collection of the objects. In Java, a separate framework named the “Collection Framework” has
been defined in JDK 1.2 which holds all the collection classes and in it.

The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two
main “root” interfaces of Java collection classes.

Need for a Separate Collection Framework

Before the Collection Framework(or before JDK 1.2) was introduced, the standard methods for
grouping Java objects (or collections) were Arrays or Vectors, or Hashtables. All of these
collections had no common interface. Therefore, though the main aim of all the collections is the
same, the implementation of all these collections was defined independently and had no correlation
among them. And also, it is very difficult for the users to remember all the different methods,
syntax, and constructors present in every collection class.

Java Collections are the one-stop solutions for all the data manipulation jobs such as
storing data, searching, sorting, insertion, deletion, and updating of data. Java collection
responds as a single object, and a Java Collection Framework provides various Interfaces
and Classes.

What is a Java Collection?

A Java Collection is a predefined architecture capable of storing a group of elements and behaving
like a single unit such as an object or a group.

and What is the Java Collection Framework?

Java Collection Framework offers the capability to Java Collection to represent a group of elements
in classes and Interfaces.

SHWETHA RANI R S 1ST BCA Page 42


OBJECT ORIENTED PROGRAMMING WITH JAVA

Java Collection Framework enables the user to perform various data manipulation operations like
storing data, searching, sorting, insertion, deletion, and updating of data on the group of elements.
Followed by the Java Collections Framework, you must learn and understand the Hierarchy of Java
collections and various descendants or classes and interfaces involved in the Java Collections.

Java Collection Framework

The following image depicts the Java Collections Hierarchy.

After the Hierarchy of Java collections; you should also get to know the various methods applied to
the Collections in Java to perform the data manipulation operations.

Java Collections Interface Methods


The table below describes the methods available to use against Java Collections for data
Manipulation Jobs.

Method Description

add() Add objects to collection.

Returns true if
isEmpty()
is empty

SHWETHA RANI R S 1ST BCA Page 43


OBJECT ORIENTED PROGRAMMING WITH JAVA

clear() Removes all elements from the collection

remove() Remove a selected object

size() Find the number of elements

stream() Return Sequential elements

toArray() Returns elements in array format

hashCode() Returns Hashcode of the elements

equals(obj X) Compare an element with the collection

iterator() Return an iterator over collection

max() Return max value in the collection

contains() Returns true is a particular value is present

JavaBeans Introduction…
• JavaBeans are reusable software components for Java
• Build re-useable applications or program building blocks called components that can be
deployed in a network on any major operating system platform.
• They are used to encapsulate many objects into a single object (the bean), so that they can be
passed around as a single bean object instead of as multiple individual objects.

SHWETHA RANI R S 1ST BCA Page 44


OBJECT ORIENTED PROGRAMMING WITH JAVA

• A JavaBeans is a Java Object that is serializable, has a 0-argument constructor, and allows
access to properties using getter and setter methods.
• Like Java applets, JavaBeans components (or "Beans") can be used to give World Wide Web
pages (or other applications) interactive capabilities such as computing interest rates or varying
page content based on user or browser characteristics.
Advantages
• A Bean obtains all of the benefits of Java's "write once, run anywhere" paradigm.
• The properties, events, and methods of a Bean that are exposed to another application can
be controlled.
• Auxiliary software can be provided to help configure a Bean.
• The configuration settings of a Bean can be saved in a persistent storage and can be
restored at a later time.
• A Bean may register to receive events from other objects and can generate events that are
sent to it.
Disadvantages
• A class with a constructor is subject to being instantiated in an invalid state. If such a class
is instantiated manually by a developer (rather than automatically by some kind of
framework), the developer might not realize that the class has been improperly
instantiated.
• The compiler can’t detect such a problem, and even if it’s documented, there’s no
guarantee that the developer will see the documentation.
• Having to create a getter for every property and a setter for many, most, or all of them, creates
an immense amount of boilerplate code.

JavaBeans API
• The JavaBeans functionality is provided by a set of classes and interfaces in the java.beans
package.

SHWETHA RANI R S 1ST BCA Page 45


OBJECT ORIENTED PROGRAMMING WITH JAVA

Network Programming Introduction…


• Network programming involves writing computer programs that enable processes to
communicate with each other across a computer network.
• Network programming is client–server programming
The process initiating the communication is a client, and the process waiting for the
communication to be initiated is a server. The client and server processes together form a
distributed system. In a peer-to-peer communication, the program can act both as a client
and a server.
Network programming is socket programming
• The endpoint in an interprocess communication is called a socket, or a network socket
• Since most communication between computers is based on the Internet Protocol, an
almost equivalent term is Internet socket.
• The data transmission between two sockets is organized by communications protocols,
usually implemented in the operating system of the participating computers. Application
programs write to and read from these sockets. Therefore, network programming is
essentially socket programming.
-Standard API
• Application programs create, control, and use sockets through system calls like socket()bind(),
listen(), connect(), send(), recv()
• The term network programming refers to writing programs that execute across multiple devices
(computers), in which the devices are all connected to each other using a network.
• The java.net package of the J2SE APIs contains a collection of classes and interfaces that
provide the low-level communication details, allowing you to write programs that focus on
solving the problem at hand.
• The java.net package provides support for the two common network protocols:

SHWETHA RANI R S 1ST BCA Page 46


OBJECT ORIENTED PROGRAMMING WITH JAVA

• TCP: TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet Protocol,
which is referred to as TCP/IP.
• UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for
packets of data to be transmitted between applications.

SHWETHA RANI R S 1ST BCA Page 47

You might also like