0% found this document useful (0 votes)
26 views98 pages

18CS45 - Ooc - Module 3

Ppt m1 ooc module 1 me hi to you and your family and friends and family members are there in the final output of the day happy birthday to you and your family and friends and family members are there in the final output of the day happy birthday to you and your family and friends and family mehhhmbers are there in the final output of the day happy birthday to you.

Uploaded by

Jontra
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)
26 views98 pages

18CS45 - Ooc - Module 3

Ppt m1 ooc module 1 me hi to you and your family and friends and family members are there in the final output of the day happy birthday to you and your family and friends and family members are there in the final output of the day happy birthday to you and your family and friends and family mehhhmbers are there in the final output of the day happy birthday to you.

Uploaded by

Jontra
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/ 98

Object Oriented Concepts

(18CS45)

Module-III

Dr. Sanchari Saha


AP, Dept of CSE,
CMRIT, Bengaluru
Course Objective:
This course (18CS45) will enable students to:
Learn fundamental features of object-oriented language and JAVA
Set up Java JDK environment to create, debug and run simple Java programs.
Create multi-threaded programs and event handling mechanisms.
Introduce event driven Graphical User Interface (GUI) programming using applets and
swings.

Course Outcome:
The student will be able to :
Explain the object-oriented concepts and JAVA.
Develop computer programs to solve real world problems in Java.
Develop simple GUI interfaces for a computer program to interact with users, and to
understand the event-based GUI handling principles using swings
CO-PO and CO-PSO Mapping

P P P P P P P
P P P P P P P P
Modules PO O O O S S S S
Course Outcomes Blooms Level O O O O O O O O
covered 5 1 1 1 O O O O
1 2 3 4 6 7 8 9
0 1 2 1 2 3 4

Explain Object-Oriented
CO1 Concepts in C++ and L2 1,2 2 3 3 2 - 2 - - 2 2 - 2 2 - 2 -
JAVA.
Develop computer
programs for solution of
CO2 L2 2,3 2 3 3 2 - 2 - - 2 2 - 2 2 - 2 -
real world problems in
Java.
Develop simple GUI
CO3 interfaces for L3 4,5 2 3 3 2 2 2 - - 2 2 - 2 2 - 2 -
interaction with users
Develop Graphical User
CO4 Interface (GUI) with use L3 5 2 3 3 3 2 2 - - 2 2 - 2 2 - 2 -
of Applets and Swings.
Text Book & Reference Book

Textbooks:
1. Sourav Sahay, Object Oriented Programming with C++ , 2nd Ed, Oxford University
Press,2006
2. Herbert Schildt, Java The Complete Reference, 7th Edition, Tata McGraw Hill, 2007.
Reference Books:
1. Mahesh Bhave and Sunil Patekar, "Programming with Java", First Edition, Pearson
Education,2008, ISBN:9788131720806
2. Herbert Schildt, The Complete Reference C++, 4th Edition, Tata McGraw Hill, 2003.
3. Stanley B.Lippmann, Josee Lajore, C++ Primer, 4th Edition, Pearson Education,
2005.
4. Rajkumar Buyya,S Thamarasi selvi, xingchen chu, Object oriented Programming
with java, Tata McGraw Hill education private limited.
5. Richard A Johnson, Introduction to Java Programming and OOAD, CENGAGE
Learning.
6. E Balagurusamy, Programming with Java A primer, Tata McGraw Hill companies
Content
➢Chapter 2:
➢Chapter 1: • Inheritance
• Classes • inheritance basics,
• Classes fundamentals • using super
• Declaring objects • creating multi level hierarchy
• Constructors • method overriding
• this keyword
• garbage collection.
➢Chapter 3:
• Exception handling in Java.
Chapter 1:
Classes fundamentals
Classes and Objects are basic concepts of Object Oriented
Programming which revolve around the real life entities.

Class

A class is a user defined blueprint or prototype from which objects


are created. It represents the set of properties or methods that are
common to all objects of one type.
In general, class declarations can include these components, in order:

Modifiers : A class can be public or has default access (Refer this for details).
Class name: The name should begin with a initial letter (capitalized by
convention).
Superclass(if any): The name of the class’s parent (superclass), if any, preceded
by the keyword extends. A class can only extend (subclass) one parent.
Interfaces(if any): A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class can implement more
than one interface.
Body: The class body surrounded by braces, { }.
class classname {
A class is declared by
type instance-variable1;
use of the class keyword.
The classes that have type instance-variable2;
been used up to this point
are actually very limited // ..
examples of its complete type instance-variableN;
form. Classes can ( and type methodname1(parameter-list)
usually do) get much {
more complex. The //body of method
general form of a class
definition is shown here: }
….
type methodnameN (parameter-list) {

//body of method
} }
Object

It is a basic unit of Object Oriented Programming and represents


the real life entities. A typical Java program creates many objects,
which as you know, interact by invoking methods. An object
consists of :
State : It is represented by attributes of an object. It also reflects
the properties of an object.
Behavior : It is represented by methods of an object. It also reflects
the response of an object with other objects.
Identity : It gives a unique name to an object and enables one
object to interact with other objects.
Example of an object : dog
When an object of a class is
created, the class is said to be
instantiated. All the instances
share the attributes and the
behavior of the class. But the
values of those attributes, i.e.
the state are unique for each
object. A single class may have
any number of instances.
Constructor in Java

A constructor in Java is a special method that is used to initialize objects. The


constructor is called when an object of a class is created. It can be used to set
initial values for object attributes:

Rules for creating Java constructor


There are two rules defined for the constructor.
• Constructor name must be the same as its class name
• A Constructor must have no explicit return type
• A Java constructor cannot be abstract, static, final, and
synchronized

There are two types of constructors in Java:

1. Default constructor (no-argument constructor)


2. Parameterized constructor
Constructor in Java

// Create a MyClass class


public class MyClass
{ // Outputs 5
int x; // Create a class attribute
// Create a class constructor for the MyClass class
public MyClass()
{
x = 5; // Set the initial value for the class attribute x
}
public static void main(String[] args)
{
// Create an object of class MyClass (This will call the constructor)
MyClass myObj = new MyClass();
// Print the value of x
System.out.println(myObj.x);
} }
//Java Program to create and call a default constructor

class Bike1
{
//creating a default constructor
Bike1()
{System.out.println("Bike is created");
}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}
}
default constructor that displays the default values
//Let us see another example of default constructor which displays the default values

class Student3
{
int id;
String name;
//method to display the value of id and name
void display()
{System.out.println(id+" "+name);
}
public static void main(String args[])
{
//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.

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


class Student4{
int id;
public static void main(String args[])
String name;
{
//creating a parameterized constructor //creating objects and passing values
Student4(int i,String n){ Student4 s1 = new Student4(111,"Karan");
id = i; Student4 s2 = new Student4(222,"Aryan");
name = n; s1.display();
} s2.display();
//method to display the values }
void display() }
{
System.out.println(id+" "+name);
}
class Student5 Constructor Overloading in Java
{
int id;
String name;
int age;
//creating two arg constructor public static void main(String args[])
Student5(int i,String n) {
{ Student5 s1 = new Student5(111,"Karan");
id = i; Student5 s2 = new Student5(222,"Aryan",25);
name = n; s1.display();
} s2.display();
//creating three arg constructor }
Student5(int i,String n,int a) }
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
Constructor Overloading in Java

class rect
{ int height, width, point; public static void main(String[] args)
public rect(int h, int w) {
{ height=h; rect r1=new rect(10,20);
width=w; rect r2=new rect(10,20,0);
} r1. area();
public rect(int h, int w, int p) r2.area();
{ height=h; }
width=w; }
point=p;
} Output:
public void area()
{ System.out.println("area="+(height*width)); area=200
} area=200
this keyword
Keyword ‘this’ is a reference variable in Java that refers to the current object.
The various usages of ‘this’ keyword in Java are as follows:

• It can be used to refer instance variable of current class


• It can be used to invoke or initiate current class constructor
• It can be passed as an argument in the method call
• It can be passed as argument in the constructor call
• It can be used to return the current class instance
The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variables and parameters,
this keyword resolves the problem of ambiguity.

Understanding the problem without this keyword


Let's understand the problem if we don't use this keyword by the
example given below: class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
rollno=rollno;
name=name;
fee=fee;
}
void display()
{ Output:
System.out.println(rollno+" "+name+" "+fee);
}
}
0 null 0.0
class TestThis1{ 0 null 0.0
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}} In the example, parameters
(formal arguments) and
instance variables are same.
So, we are using this keyword
to distinguish local variable and
instance variable.
Solution of the above problem by this keyword

class Student{ class TestThis2{


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

111 ankit 5000


112 sumit 6000
Garbage Collection

There is no concept of destructor in Java. In place of the destructor, Java provides


the garbage collector that works the same as the destructor. The garbage collector is
a program (thread) that runs on the JVM

In Java destruction of object from memory is done automatically by the JVM.


When there is no reference to an object, then that object is assumed to be no longer
needed and the memories occupied by the object are released. This technique is called
Garbage Collection. This is accomplished by the JVM.

Advantages of Garbage Collection


1. Programmer doesn't need to worry about
dereferencing an object.
2. It is done automatically by JVM.
3. Increases memory efficiency and
decreases the chances for memory leak.
How Java Garbage Collection Works

In the first step, unreferenced objects are identified and marked as ready for
garbage collection.

In the second step, marked objects are deleted. Optionally, memory can be
compacted after the garbage collector deletes objects, so remaining objects are
in a contiguous block at the start of the heap. The compaction process makes it
easier to allocate memory to new objects sequentially after the block of memory
allocated to existing objects.
How can an object be unreferenced?

1) By nulling a reference:
Employee e=new Employee();
e=null;

2) By assigning a reference to another:


Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage
collection

3) By anonymous object:
new Employee();
Using finalize() method
finalize method in java is used to release all the resources used
by the object before it is deleted/destroyed by the Garbage
collector. finalize() is not a reserved keyword in java, it's a
method. Once the clean-up activity is done by the finalize()
method garbage collector immediately destroys the java object.
This method is defined in Object class as:

protected void finalize()


{
}
gc() method

The gc() method is used to invoke the garbage collector. by using the
gc() method, we can request JVM to run Garbage Collector. The gc()
is found in System and Runtime classes.

• The finalize() method is called by Garbage Collector gc(), not JVM.


• The finalize() method is never invoked more than once for any
object.
Simple Example of garbage collection in java
public class TestGarbage1
{
public void finalize()
{
Output: System.out.println("object is garbage
collected");
object is garbage collected
}
object is garbage collected
public static void main(String args[])
{
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Chapter 2:
Inheritance
• As the name suggests, inheritance means to take something that is already made.
It is one of the most important features of Object Oriented Programming. It is the
concept that is used for reusability purpose.
• Inheritance is the mechanism through which we can derive classes from other
classes.
• The derived class is called as child class or the subclass or we can say the
extended class and the class from which we are deriving the subclass is called the
base class or the parent class.
• To derive a class in java the keyword extends is used. The following kinds of
inheritance are there in java.

Why use inheritance in java


• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.
Types of Inheritance

Java doesn’t support Multiple inheritance but we can achieve this


through the concept of Interface.
Single level/Simple Inheritance

When a subclass is derived simply from its parent class then this
mechanism is known as simple inheritance. In case of simple
inheritance there is only a sub class and its parent class. It is also called
single inheritance or one level inheritance.

The syntax for creating a subclass is simple. At the beginning


of your class declaration, use the extends keyword, followed
by the name of the class to inherit from:
class A
{

class B extends A //B is a subclass of super class A.


{

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

• When a subclass is derived from a derived class then this


mechanism is known as the multilevel inheritance.

• The derived class is called the subclass or child class for it's
parent class and this parent class works as the child class for it's
just above ( parent ) class.

• Multilevel inheritance can go up to any number of level


Import java.util.*; class Cube extends Rectangle
class Shape {
{ int s=10;
public void display() public void volume() {
{ System.out.println(“volume=” +(s*s*s));
System.out.println(“ shape is }
polygon” ); }
} public class Tester {
} public static void main(String[] arguments)
class Rectangle extends Shape {
{ Cube c = new Cube();
int l=10; int b=20; c.display();
public void area() { c.area();
System.out.println (“area=” +(l*b)); c.volume();
} } }
Output
} shape is polygon
area=200
volume=1000
public class Maruti800 extends Maruti {
class Car {
public Car()
public Maruti800()
{
{
System.out.println("Class Car");
System.out.println("Maruti Model:
}
800");
public void vehicleType()
}
{
public void speed()
System.out.println("Vehicle Type: Car");
{
}
System.out.println("Max: 80Kmph");
}
}
class Maruti extends Car {
public static void main(String args[])
public Maruti()
{
{
Maruti800 obj=new Maruti800();
System.out.println("Class Maruti");
obj.vehicleType();
}
obj.brand();
public void brand()
obj.speed();
{
} }
System.out.println("Brand: Maruti");
Output:
}
//constructor call in a hierarchy of parent classes
public void speed()
Class Car
{
Class Maruti
System.out.println("Max: 90Kmph");
Maruti Model: 800
}
Vehicle Type: Car
}
Brand: Maruti
Max: 80Kmph // function overriding in sub class
super keyword

The super is java keyword. As the name suggest super is used


to access the members of the super class. Here member can
either be an instance variable or a method

Example Usage: Suppose class A is the super class that has two
instance variables as int a and float b. class B is the subclass that
also contains its own data members named a and b. then we can
access the super class (class A) variables a and b inside the
subclass class B just by calling the following command.

super. Member;
This form of super keyword is most useful to handle situations
where the local members of a subclass hides the members of a
super class having the same name. The following example
clarifies all the confusions.

class A
{
int a;
float b;
void Show()
{
System.out.println("b in super class: " +
b);
}
}
class B extends A
{
class Mypgm
int a;
{
float b;
public static void main(String[] args)
B( int p, float q)
{
{
B subobj = new B(1, 5);
a = p;
subobj.Show();
super.b = q;
}
}
}
void Show()
{
super.Show();
OUTPUT
System.out.println("b in super class: " + super.b);
b in super class: 5.0
System.out.println("a in sub class:" + a);
b in super class: 5.0
}
a in sub class: 1
}
Use of super to call super class constructor:

The second use of the keyword super in java is to call super class
constructor in the subclass. This functionality can be achieved just
by using the following command.

super(parameter list);

Here parameter list is the list of the parameter requires by the


constructor in the super class. super must be the first statement
executed inside a super class constructor. If we want to call the
default constructor then we pass the empty parameter list. The
following program illustrates the use of the super keyword to call a
super class constructor.
class B extends A
{
class A int d;
{ B(int l, int m, int n, int o)
int a; int b; int c; {
A(int p, int q, int r) super(l,m,n);
{ d=o;
a=p; b=q; c=r; }
}
} void show()
{
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
class Mypgm
{
public static void main(String args[])
{
B b = new B(4,3,8,7);
b.Show();
}
}

OUTPUT
a=4
b=3
c=8
d=7
Method Overriding

Method overriding in java means a subclass method overriding


a super class method.

Superclass method should be non-static. Subclass uses


extends keyword to extend the super class. In the example
class B is the sub class and class A is the super class. In
overriding methods of both subclass and superclass possess
same signatures. Overriding is used in modifying the methods
of the super class. In overriding return types and constructor
parameters of methods should match.
Below example illustrates method overriding in java.

class A
class B extends A
{
{
int i;
int j;
A(int a, int b)
B(int a, int b, int c)
{
{
i = a+b;
super(a, b);
}
void add()
j = a+b+c;
{
}
System.out.println("Sum of a and b is: " +
void add()
i);
{
}
super.add();
}
System.out.println("Sum of a, b and c is: " + j);
}
}
class MethodOverriding
{
public static void main(String args[]) OUTPUT
Sum of a and b is: 30
{ Sum of a, b and c is: 60
B b = new B(10, 20, 30);
b.add();
}
}
Method overriding form a basis for Dynamic Method Dispatch

Method overriding forms the basis for one of Java’s most powerful
concepts: dynamic method dispatch. Dynamic method dispatch is
the mechanism by which a call to an overridden method is resolved
at run time, rather than compile time. Dynamic method dispatch is
important because this is how Java implements run-time
polymorphism.

Let’s begin by restating an important principle: a superclass


reference variable can refer to a subclass object. Java uses this fact
to resolve calls to overridden methods at run time.
Here is how. When an overridden method is called through a superclass
reference, Java determines which version of that method to execute based
upon the type of the object being referred to at the time the call occurs.
Thus, this determination is made at run time. When different types of
objects are referred to, different versions of an overridden method will be
called. In other words, it is the type of the object being referred to (not the
type of the reference variable) that determines which version of an
overridden method will be executed. Therefore, if a superclass contains a
method that is overridden by a subclass, then when different types of
objects are referred to through a superclass reference variable, different
versions of the method are executed.
Here is an example that illustrates dynamic method dispatch:

// Dynamic Method Dispatch


class A class C extends A { // override callme()
{
void callme() void callme() {
{
System.out.println("Inside A's callme method"); System.out.println("Inside C's callme method");
}
}

class B extends A }
{
void callme()
{
System.out.println("Inside B's callme method"); }

}
}
class Dispatch
{ r = c; // r refers to a C object
public static void main(String args[]) r.callme(); // calls C's version of callme
{
}
A a = new A(); // object of type A }
B b = new B(); // object of type B

C c = new C(); // object of type C The output from the program is shown here:

A r; // obtain a reference of type A Inside A's callme method


Inside B's callme method
r = a; // r refers to an A object Inside C's callme method

r.callme(); // calls A's version of callme

r = b; // r refers to a B object

r.callme(); // calls B's version of callme


This program creates one superclass called A and two subclasses
of it, called B and C. Subclasses B and C override callme(
)declared in A. Inside the main( ) method, objects of type A, B, and
C are declared. Also, a reference of type A, called r, is declared.
The program then in turn assigns a reference to each type of object
to r and uses that reference to invoke callme( ). As the output
shows, the version of callme( ) executed is determined by the type
of object being referred to at the time of the call. Had it been
determined by the type of the reference variable, r, you would see
three calls to A’s callme( ) method.
Method Overloading

class MethodOverloading
Two or more methods have the {
same names but different int add( int a,int b)
{
argument lists. The arguments return(a+b);
}
may differ in type or number, or float add(float a,float b)
both. However, the return types {
return(a+b);
of overloaded methods can be }
the same or different is called double add( int a, double b,double c)
{
method overloading. An return(a+b+c);
}
example of the method
}
overloading is given below:
class MainClass
{
public static void main( String arr[] )
{
MethodOverloading mobj = new MethodOverloading ();
System.out.println(mobj.add(50,60));
System.out.println(mobj.add(3.5f,2.5f));
System.out.println(mobj.add(10,30.5,10.5));
}
}

OUTPUT
110
6.0
51.0
Java program of addition and subtraction of two Complex Numbers

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

ComplexNumber c1 = new ComplexNumber(2, 4);


ComplexNumber c2 = new ComplexNumber(3, 5);

ComplexNumber sum = c1.sum(c2);


ComplexNumber difference = c1.difference(c2);

System.out.println("first complex number: " + c1);


System.out.println("second complex number: " + c2);
System.out.println("sum of two complex numbers: " + sum);
System.out.println("difference of two complex numbers: " + difference);

}
}
class ComplexNumber {
private final double real;
private final double imaginary;

public ComplexNumber(double real, double imaginary) {


this.real = real;
this.imaginary = imaginary;
}

public ComplexNumber sum(ComplexNumber other) {


double r = this.real + other.real;
double i = this.imaginary + other.imaginary;
return new ComplexNumber(r, i);
}
public ComplexNumber difference(ComplexNumber other)
{
double r = this.real - other.real;
double i = this.imaginary - other.imaginary;
return new ComplexNumber(r, i);
}

public double getReal() {


return real;
}
Output
public double getImaginary() first complex number: 2.0 + 4.0i
{ second complex number: 3.0 + 5.0i
return imaginary; sum of two complex numbers: 5.0 + 9.0i
} difference of two complex numbers: -1.0 + -
1.0i
public String toString()
{
return real + " + " + imaginary + "i";
}

}
Abstract Class & Abstract Method in Java

A class which is declared with the abstract keyword is known as an abstract


class in Java. It can have abstract and non-abstract methods (method with
the body).
Points to Remember
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• Abstract classes cannot be instantiated, but they can be subclassed.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change the body
of the method.

Syntax of abstract class


abstract class A{}
abstract class Language {

// regular method of abstract class


public void display() {
System.out.println("This is Java Programming");
}
}

class Main extends Language {

public static void main(String[] args) {

// create an object of Main


Main obj = new Main();

// access method of abstract class using object of Main class


obj.display();
}
}
A method which is declared as abstract and does not have
implementation is known as an abstract method.

Syntax of abstract method


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

abstract class Animal {


abstract void makeSound(); // abstract method
class Main {
public void eat() // non abstract method
public static void main(String[] args) {
{
System.out.println("I can eat.");
// create an object of Dog class
}
Dog d1 = new Dog();
}
d1.makeSound();
class Dog extends Animal {
d1.eat();
}
// provide implementation of abstract method
}
public void makeSound() {
System.out.println("Bark bark");
}
}
If a class includes abstract methods, then the class itself must be
declared abstract, as in:

public abstract class GraphicObject


{
// declare fields
// declare nonabstract methods
abstract void draw();
}
When an abstract class is subclassed, the subclass usually
provides implementations for all of the abstract methods in its
parent class. However, if it does not, then the subclass must also
be declared abstract.
Accesses Constructor of Abstract Classes
An abstract class can have constructors like the regular class. And, we can access the
constructor of an abstract class from the subclass using the super keyword. For
example,

abstract class Animal


{
Animal() {
….
}
}
class Dog extends Animal
{
Dog() {
super();
...
}
}
Here, we have used the super() inside the constructor of Dog to access the constructor
of the Animal.
abstract class MotorBike {
abstract void brake(); Example Program -1
}

class SportsBike extends MotorBike {

// implementation of abstract method class Main {


public void brake() { public static void main(String[] args) {
System.out.println("SportsBike Brake"); MountainBike m1 = new MountainBike();
} m1.brake();
} SportsBike s1 = new SportsBike();
s1.brake();
class MountainBike extends MotorBike { }
}
// implementation of abstract method
public void brake() {
System.out.println("MountainBike Brake");
}
}
abstract class Shape{
abstract void draw(); Example Program -2
}
class Rectangle extends Shape
{
void draw()
{System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw()
{System.out.println("drawing circle");}
}
class TestAbstraction1{
public static void main(String args[]){
Rectangle r=new Rectangle();
Circle1 c= new Circle1();
r.draw(); c.draw();
}
}
final Keyword in Java
The final keyword in java is used to restrict the user. The final keyword
can be used in many context. Final can be:

1. variable
2. method
3. class

1) final variable: If you make any variable as final, you


cannot change the value of final variable(It will be constant).

Example: There is a final variable speedlimit, we are going to change


the value of this variable, but It can't be changed because final variable
once assigned a value can never be changed.
class Bike
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
Output: Compile Time Error
}
}
Class MyPgm
{
public static void main(String args[])
{
Bike obj=new Bike();
obj.run();
}
}
2) final method: If you make any method as final, you cannot override it.

Example:

class Bike
Class MyPgm
{
{
final void run()
public static void main(String args[])
{
{
System.out.println("running");
Honda honda= new Honda();
}
honda.run();
}
}
class Honda extends Bike
}
{
Output:Compile Time Error
void run()
{
System.out.println("running safely with 100kmph");
}
}
3) final class:If you make any class as final, you cannot extend it, i.e cannot create
any subclass from it.

Example:
Class MyPgm
final class Bike {
{
public static void main(String args[])
} {
Honda honda= new Honda();
class Honda extends Bike honda.run();
{ }
void run() }
{ Output:Compile Time Error
System.out.println("running safely with 50kmph");
}
}
Chapter 3:
Exception handling in Java

An Exception, It can be defined as an abnormal event that occurs


during program execution and disrupts the normal flow of instructions.
The abnormal event can be an error in the program.

Errors in a java program are categorized into two groups:

1. Compile-time errors occur when you do not follow the syntax of a


programming language.
2. Run-time errors occur during the execution of a program.
Concepts of Exceptions

An exception is a run-time error that occurs during the execution of a java


program.

Example: If you divide a number by zero or open a file that does not exist, an
exception is raised.

In java, exceptions can be handled either by the java run-time system or by a user-
defined code. When a run-time error occurs, an exception is thrown.

The unexpected situations that may occur during program execution are:

• Running out of memory


• Resource allocation errors
• Inability to find files
• Problems in network connectivity
Exception handling techniques:

Java exception handling is managed via five keywords they are:

1. try: try
2. catch. {
3. throw. Exception handling Statement <code>
}
Syntax
4. throws. catch (<exception type1>
5. finally. <parameter1>)
Exceptions are handled using a {
try-catch-finally construct, // 0 or more<statements>
which has the Syntax.
}
finally
{
// finally block<statements>
}
1. try Block: The java code that you think may produce an
exception is placed within a try block for a suitable catch block to handle
the error.

If no exception occurs the execution proceeds with the finally block else
it will look for the matching catch block to handle the error.

Again if the matching catch handler is not found execution proceeds with
the finally block and the default exception handler throws an exception.

2. catch Block: Exceptions thrown during execution of the try block


can be caught and handled in a catch block. On exit from a catch block,
normal execution continues and the finally block is executed (Though the
catch block throws an exception).
3. finally Block: A finally block is always executed,
regardless of the cause of exit from the try block, or whether any
catch block was executed. Generally finally block is used for
freeing resources, cleaning up, closing connections etc.
Java’s Built in Exceptions

Exception Classes Description


ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an
incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an
unlocked thread.
IllegalStateException Environment or application is in incorrect
state.
IllegalThreadStateException Requested operation not compatible with
current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric
format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a
string.
UnsupportedOperationException An unsupported operation was encountered.
Example:
public class ExcepTest
{ The array is declared with 2 elements. Then the code
public static void main(String args[]) tries to access the 3rd element of the array which
{ throws an exception.
try
{
int a[] = new int[2];
System.out.println("Access element three :" + This would produce following
a[3]); result:
}
catch(ArrayIndexOutOfBoundsException e) Exception thrown
{ :java.lang.ArrayIndexOutOfBoundsExc
System.out.println("Exception thrown :" + e); eption: 3 Out of the block
}
System.out.println("Out of the block");
}
}
Problem without exception handling

Let's try to understand the problem if we don't use a try-catch block.

Example 1
As displayed in the above
public class TryCatchExample1 { example, the rest of the code is
not executed (in such case, the
public static void main(String[] args) {
rest of the code statement is not
int data=50/0; //may throw exception printed).
There might be 100 lines of code
System.out.println("rest of the code"); after the exception. If the
exception is not handled, all the
} code below the exception won't
be executed.
}
Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero


Solution by exception handling
Let's see the solution of the above problem by a
java try-catch block.

public class TryCatchExample2 {

public static void main(String[] args) {


try
{ Output:
int data=50/0; //may throw exception java.lang.ArithmeticException: / by
} zero
//handling the exception rest of the code
catch(ArithmeticException e) As displayed in the above example,
{ the rest of the code is executed, i.e.,
System.out.println(e); the rest of the code statement is
} printed.
System.out.println("rest of the code");
}

}
try catch block Example 1

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
//rest code of the program
System.out.println("rest of the code...");
}
}
try catch block Example 2
This would produce following
result:
public class ExcepTest
{
Exception thrown
public static void main(String args[]) :java.lang.ArrayIndexOutOfBoundsException: 3
{ Out of the block
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");
}
}
Multiple catch Blocks:

A try block can be followed by multiple catch blocks. The syntax for
multiple catch blocks looks like the following:

try
{
// code
}
catch(ExceptionType1 e1)
{
//Catch block
}
catch(ExceptionType2 e2)
{
//Catch block
}
catch(ExceptionType3 e3)
{
//Catch block
}
class Multi_Catch
The previous statements {
demonstrate three catch blocks, public static void main (String args [])
but you can have any number of {
them after a single try.
try
{
Example: Here is code int a=args.length; System.out.println(“a=”+a);
segment showing how to int b=50/a;
int c[]={1};
use multiple try/catch
}
statements. catch (ArithmeticException e)
{
System.out.println ("Division by zero");
OUTPUT }
Division by zero
array index out of bound catch (ArrayIndexOutOfBoundsException e)
{
System.out.println (" array index out of bound");
}
}
}
4. throw: Java throw keyword is used throw an exception
explicitly in the code, inside the function or the block of code.
The throw keyword is followed by an instance of Exception to be
thrown. throw is used within the method.
We are allowed to throw only one exception at a time i.e. we
cannot throw multiple exceptions.

5.throws: Java throws keyword is used in the method signature


to declare an exception which might be thrown by the function
while the execution of the code.

The throws keyword is followed by class names of Exceptions to


be thrown. throws is used with the method signature. We can
declare multiple exceptions using throws keyword that can be
thrown by the method. For example, main() throws IOException,
SQLException.
throw Example 1

public class GFG {


public static void main(String[] args)
{
// Use of unchecked Exception
try {
// double x=3/0;
throw new ArithmeticException();
}
catch (ArithmeticException e) {
e.printStackTrace();
}
}
}
throw Example 2

public class JavaTester{


public void checkAge(int age){
if(age<18)
throw new ArithmeticException("Not Eligible for voting");
else
System.out.println("Eligible for voting");
}
public static void main(String args[]){
JavaTester obj = new JavaTester();
obj.checkAge(13);
System.out.println("End Of Program");
}
}
throws Example 1 public class GFG {

public static void writeToFile() throws Exception


{
BufferedWriter bw = new BufferedWriter(
new FileWriter("myFile.txt"));
bw.write("Test");
bw.close();
}

public static void main(String[] args) throws Exception


{
try {
writeToFile();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
throws Example 2
public class JavaTester
{
public int division(int a, int b) throws ArithmeticException
{
int t = a/b;
return t;
}
public static void main(String args[]){
JavaTester obj = new JavaTester();
try{
System.out.println(obj.division(15,0));
}
catch(ArithmeticException e){
System.out.println("You shouldn't divide number by zero");
}
}
}
Points to remember

● Program statements that you want to monitor for exceptions are


contained within a try block.
● If an exception occurs within the try block, it is thrown.
● Your code can catch this exception, using catch, and handle it.
● System generated exceptions are automatically thrown by the
Java run-time system.
● To manually throw an exception, use the keyword throw.
● Any exception that is thrown out of a method must be specified
as such by throws clause.
● Any code that absolutely must be executed after the try block
completes is put in a finally block
finally
The finally clause is written with the try-catch statement. It is
guaranteed to be executed after a catch block or before the
method quits.

try
Syntax {
// statements
}
catch (<exception>
obj)
{
// statements
}
finally
{
//statements
}
Take a look at the following example which has a catch and a finally block. The
catch block catches the ArithmeticException which occurs for arithmetic error like
divide-by-zero. After executing the catch block the finally is also executed and you
get the output for both the blocks.

class Finally_Block
{ class Mypgm
static void division ( ) {
{ public static void main(String args[])
try {
{
int num = 34, den = 0; int quot = num / den;
} Finally_Block
catch(ArithmeticException e) f=new Finally_Block();
{ f.division ( );
System.out.println ("Divide by zero"); }
} }
finally
{ OUTPUT
System.out.println ("In the finally block"); Divide by zero
} In the finally block
}
try
{
// statements
// statements
Nested try Statements
try
{
Just like the multiple catch blocks, // statements
// statements
we can also have multiple try }
blocks. These try blocks may be catch (<exception_two> obj)
{
written independently or we can // statements
nest the try blocks within each }

other, i.e., keep one try-catch block // statements


within another try-block. The // statements
}
program structure for nested try catch (<exception_two> obj)
statement is: {
// statements
}
Consider the following example in which you are accepting two numbers
from the command line. After that, the command line arguments, which
are in the string format, are converted to integers.

If the numbers were not received properly in a number format, then


during the conversion a NumberFormatException is raised otherwise the
control goes to the next try block. Inside this second try-catch block the
first number is divided by the second number, and during the calculation
if there is any arithmetic error, it is caught by the inner catch block.
class Nested_Try
{
public static void main (String args [ ] ) catch (ArithmeticException e)
{ {
try System.out.println("divide by zero");
{ }
int a = Integer.parseInt (args [0]); }
int b = Integer.parseInt (args [1]); catch (NumberFormatException e)
int quot = 0; {
try System.out.println ("Incorrect argument type");
{ }}}
quot = a / b;
System.out.println(quot);
}
The output of the program is:
If the arguments are entered properly in the command prompt like:
java Nested_Try 2 4 6
4
If the argument contains a string than the number:
java Nested_Try 2 4 aa Incorrect argument type

If the second argument is entered zero:

java Nested_Try 2 4 0
divide by zero
Chained Exception
Chained Exception was added to Java in JDK 1.4. This feature
allows you to relate one exception with another exception, i.e one
exception describes cause of another exception. For example,
consider a situation in which a method throws an
ArithmeticException because of an attempt to divide by zero but the
actual cause of exception was an I/O error which caused the divisor
to be zero. The method will throw only ArithmeticException to the
caller. So the caller would not come to know about the actual cause
of exception. Chained Exception is used in such type of situations.

Two new constructors and two new methods were added to


Throwable class to support chained exception.

• Throwable(Throwable cause)
• Throwable(String str, Throwable cause)
In the first constructor, the paramter cause specifies the actual cause of
exception. In the second form, it allows us to add an exception description
in string form with the actual cause of exception.

getCause() and initCause() are the two methods added to Throwable


class.

getCause() method returns the actual cause associated with current


exception.
initCause() set an underlying cause(exception) with invoking exception.
Lets understand the import java.io.IOException;
chain exception with the
public class ChainedException
help of an example, here, {
ArithmeticException was public static void divide(int a, int b)
thrown by the program {
but the real cause of if(b == 0)
exception was {
ArithmeticException ae = new
IOException. We set the ArithmeticException("top layer");
cause of exception using ae.initCause(new IOException("cause"));
initCause() method. throw ae;
}
else
{
System.out.println(a/b);
}
}
public static void main(String[] args)
{
try
{
divide(5, 0);
}
catch(ArithmeticException ae) {
System.out.println( "caught : " +ae);
System.out.println("actual cause: "+ae.getCause());
}
}
}
Output:
caught:java.lang.ArithmeticException: top layer
actual cause: java.io.IOException: cause
Question Bank
Explain various types of constructors along with example program
What is the need of this pointer? How it helps us in programming? Explain with a
program
How inheritance helps us in programming? Justify your answer. Explain single level
inheritance with an example program.
Explain how the super keyword is used to access member variable, member
function and call the super class constructor.
Explain the working steps of garbage collection.
Explain the various ways by which the keyword super can be used in a program.
Explain with supporting programs.
What are the various types of inheritance? With an example program explain how
member variables and members functions of a super class can be inherited by a sub
class in single level inheritance.
Explain multilevel inheritance with a pictorial presentation. Write an example
program for creating multilevel inheritance.
Compare method overriding and method overloading. Explain the concept of
method overriding with an example program.
How ‘final’ keyword can be used in program? Justify your answer with an example
program.
Explain the possible ways for handling exception in a program. For each mechanism,
write relevant program.
List various built-In exceptions that are present in Java .
Write an example program showing the use of try, catch and finally keyword for
handling exception.
What is throw and throws? Give syntax for both and explain with an example.
Differentiate between throw and throws keyword for handling exception
Create a try block that is likely to generate three types of exception and incorporate
necessary catch blocks to catch and handle them.
What is a nested try statement? Give an example for nested try statement.
Write a Java program to illustrate the exception handling when a number is divided by zero and an
array has a negative index value.
Explain with an example program how finalize() method is useful in garbage collection. Why Java
does not support destructors? Justify your answer.
Explain how constructor overloading helps us in programming. Create a class called math techniques
that supports the following constant and method:
(i)pi=3.14 (ii)area of rectangle(iii)area of circle(iv)area of triangle
Using constructor overloading concept write a program to calculate and display area of rectangle,
circle, triangle.
Write the syntax for try and catch block to handle multiple exceptions.
Use abstract class called shape which has three subclasses say triangle, rectangle, circle. Define one
method area() in the abstract class and override this area () in these three subclasses to calculate for
specific object i.e. area() of triangle subclass should calculate area of triangle and the same concept
applies for circle and rectangle.
“If we declare a particular class as final, no class can be derived from it”. Justify this statement with
an example program

You might also like