18CS45 - Ooc - Module 3
18CS45 - Ooc - Module 3
(18CS45)
Module-III
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
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
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.
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:
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;
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:
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.
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.
}
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
• 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.
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);
OUTPUT
a=4
b=3
c=8
d=7
Method Overriding
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.
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:
r = b; // r refers to a B object
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;
}
}
class ComplexNumber {
private final double real;
private final double imaginary;
}
Abstract Class & Abstract Method in Java
1. variable
2. method
3. class
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
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:
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.
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:
}
try catch block Example 1
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.
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 }
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.
• 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.