Java (Sem 4) Unit 3
Java (Sem 4) Unit 3
Groups UNIT – 3
Unit – 3
Polymorphism
Interfaces
Packages
Exception Handling
__________________________________________________________________________
A) Since Java is object-oriented language , it supports Polymorphism . It means “ one can have many forms “.
In java, it is implemented with concepts “Method Over Loading and Method OverRiding“.
Here different parameter list means changing the number or type of parameters.
Sometimes if required we can change the definition also, i.e. a single method performs different operations.
Example program
class Shape
{
void area(float radius) // one float parameter
{
System.out.println(“Area of Circle : “+ (3.14*radius *radius));
}
void area(int length , int width) // same method with two int parameters
{
System.out.println(“Area of Rectangle : “+ (length * width));
}
}
class MOverLoad
{
public static void main ( String args[ ] )
{
Shape x = new Shape();
x.area(7.5 f ); // calculates area of circle
x.area(10 , 20 ); // same method calculates area of Rectangle also
}}
We can perform Method overloading for the methods which are declared as private ,static and final also as shown in
below Example code :
class Shape
{
private static final void area(float radius) // one float parameter
{
System.out.println(“Area of Circle : “+ (3.14*radius *radius));
}
private static final void area(int length , int width) // same method with two int params
{
System.out.println(“Area of Rectangle : “+ (length * width));
}
}
**Method OverRiding( Dynamic/ Run Time Polymorphism) : It is process of change (override /change ) the
definition of Super class method in its Sub class .
In this process , we does not change return type and parameter list.
class A
{
int x ;
void display( )
{
System.out.println(“From class A , x = “+x);
}
definition of }
display ( ) class B extends A
method changed in {
sub class void display( )
{
System.out.println(“ From class B, x*x =“ +(x*x));
System.out.println(“Method Overriding”);
}
}
classOverRide
{
public static void main(String args[ ])
{
A a=new A( );
a.x=5;
a.display( );
B b =new B( );
b.x=5;
b.display( );
}
}
Output : From class A , x = 5
From class B , x*x = 25 Method Overriding
We can perform Method OverRiding for static methods but not possible with private and final methods
Static method (No Error) private and final methods (Give Error)
class A class A
{ {
static void display( ) private final void display( )
{ {
System.out.println(“From class A , x = “+x ) ; System.out.println(“From class A , x = “+x ) ;
} }
} }
class B extends A class B extends A
{ {
static void display( ) private final void display( )
{ {
System.out.println(“From class B , x*x = “+(x*x) ) ; System.out.println(“From class B , x*x = “+(x*x) ) ;
System.out.println(“Method Overriding”); System.out.println(“Method Overriding”);
} }
} }
………………………………………………………………………………………………………………………………………………………….
Q) Explain about final variables ,final methods, final classes and finalizer
Generally using Inheritance concept , we can use and change the variables and methods of Super class in its
related Subclasses. But we can restrict (stop) this changing of superclass properties in subclasses by using final
keyword.
final variables :
The variables declared with final keyword are called “final variables”.
These cannot be changed in subclasses.
final methods :
The methods declared with final keyword are called “final methods”.
These cannot be changed in subclasses.
The following program shows the working of final variables and methods :
class A
{
final int x ;
final void display( )
{
System.out.println(“x : “+x);
}
gives error when }
display ( ) class B extends A
method changed {
in subclass void display( )
{
System.out.println(“x * x : “ +(x*x));
System.out.println(“Method Overriding”);
}}
As shown above , the Superclass properties which are declared with final cannot be changed in its Sub classes .
final classes :
The classes declared with final keyword are called “final classes”
These classes cannot be inherited to Subclasses.
Ex : final class A
{
______
______
}
class B extends A /* gives error because A is final class */
{
______
______
}
abstract methods :
The methods which are declared with “abstract” keyword are called “abstract methods”.
These must be overridden (redefined) in its related Subclasses.
These have only declaration (return type and parameter list) not definition(body of method)
abstract classes :
The classes which have abstract methods are called “abstract classes”.
These are declared with abstract keyword and must be Sub classed.
abstract class A
{
abstract void display( ) ; //only method declaration
abstract method }
display ( ) class B extends A
defined {
in subclass void display( )
{
System.out.println(“welcome”);
System.out.println(“abstract method”);
}
}
As shown above, the methods which are declared as “abstract” are must be defined in related subclasses.
Rules to declare abstract methods and classes :
we cannot create objects directly for abstract classes.
abstract methods should be defined in related Sub classes.
cannot declare constructors and static methods as abstract.
_____________________________________________________________________________________________________
Chapter -2 INTERFACES
Q )Explain about Interfaces (or) Explain declaring, implementing and Extending of Interfaces.
Interface : It is also like class which is combination of variables and methods .But contains only final variables and
abstract methods.
The Interfaces are developed and used in java programs are as follows :
Declaring a Interface
Implementing a Interface
Extending a Interface
/* Declaring Interface */
interface A
{
final static int x=10 ;
public void display ( ) ;
}
/* implementing Interface */
class B implements A
{
public void display ( )
{
System.out.println(“x value = “ + x) ;
} }
}
B b=new B( );
A a;
a=b;
a.display( );
}
}
Extending a Interface :
Like classes , Interfaces are participated in Inheritance by using extends keyword.
Then the variables and methods of an Interface are accessed by another Interface.
ex : interface A
{
int x =10;
void displayA( );
}
interface B extends A /* interface B is derived from interface A */
{
int y=20;
void displayB( );
}
class C implements B
{
void displayA ( )
{
System.out.println(“x value = “ + x) ;
}
void displayB ( )
{
System.out.println(“y value = “ + x) ;
}
}
Since interface B is derived from A , when class C implementing interface Bthe variables and methods of interface A
also used by class C through B .
________________________________________________________________________________________
Multiple Inheritance : If Single Sub Class is derived from more than one Super Class , it is
called “Multiple Inheritance “ . It is represented as :
Here the Sub Class C is derived from two Super Classes A and B .
In Java , the Multiple Inheritance is not possible with classes. But by using “ Interfaces“ concept, we can develop
Multiple Inheritance as follows :
interface A
{
int x=10 ;
public void displayA ( ) ;
}
class B
{
int y=20;
void displayB ( )
{
System.out.println(“y value = “ + y) ;
}
}
class C extends B implements A /* C derived from A and B */
{
public void displayA ( )
{
System.out.println(“x value =”+ x) ;
}
}
class Multiple
{
public static void main( String args[ ] )
{
C k =new C ( );
As shown above , the class C is derived from two (more than one )super classes A and B . similarly , class C can use the
properties of both A and B.
In this way we can develop Multiple Inheritance using Interfaces in Java.
___________________________________________________________________________________________________________
Chapter -3 PACKAGES
Package :Package is the group of classes , interfaces etc. These classes are used by
other programs by importing that package.
Types of Packages :In Java, Packages are two types. They are :
1.System Defined(Java API) Built-in Packages
2. User Defined Packages
Creating a Package
Adding a class to existing Package
Importing Packages
Creating a Package : It is the process of declaring a package name and defining
classes for that package.
To declare a package we a special keyword “package” as follows :
Example : package P1 ;
public class A
{
public int x ;
public void displayA( )
{
System.out.println(“ From class A in pack P1 , x = “ + x );
}
}
It is possible to add one more class/interface to the same Package. For Example ,
the above package ‘P1 ’ contains class A. Now we can add another an interface I to
the package P1
For this ,open another notepad file and type as follows :
package P1;
public interface K
{
public void show( ) ;
Importing Packages :To use the classes of a package, we need to import the
packages into our programs. For this, we use keyword “ import” as follows :
The following program shows how to import package P1 into another program.
open new notepad file and type as follows :
import P1.A ;
import P1.B ;
Now save the above code as “ use_pack.java “ in the drive where folder P1 exists.
After that compile and execute “use_pack.java “ at command prompt as follows :
C:>javac use_pack.java
Note 1: In the above program(use_pack.java) , we are not defining classes A and B but
we are using those classes by importing package P1 into our program , since P1
contains classes A and B.
Note 2: This is main advantage of creating packages. i.e. the classes/interfaces of one
program are used in another program.
.........................................................................................................................
choice Q ) Explain the following :
Sometimes it is need to extend ( derive new classes ) from the classes of a package
into our program. For this , import that package and derive new classes by using
the keyword “extends “ ( like Inheritance programs ).
package P1 ;
public class A
{
public int x ;
public void display( )
{
System.out.println(“ From class A in pack P1 , x = “ + x );
}
}
Now we derive a new class C from class A in another new program as follows :
import P1.A;
class C extends A
{
void displayC()
{
System.out.println(“ C derived from A , x = “ + x ) ;
}
}
class Ext_pack
{
public static void main( String args[ ] )
{
C obj = new C ( );
Krishnaveni Degree College :: Narasaraopet page 11
OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3
Sometimes there is need to stop the accessing ( importing ) of classes from the
package into another programs. This is called “ hiding of classes “ .
For this process , we declare the classes as “ not public “ ,i.e. the keyword “public”
should not use before class definition.
package P1 ;
public class A
{
-------
-------
}
class B
{
-------
-------
}
As shown above the class B is not declared with “public” , so it is not accessible into
other programs . But class A is accessible in other programs.
....................................................................................................................
Sometimes a package may contain other sub packages also. i.e. a package is
defined in other (already existed) package. Then we can import those sub packages in
Hierarchical manner as follows
Here java and P are the main packages .awt and p1 are sub packages. Color and B
are classes defined in sub packages.
Now create a new folder sp should as sub folder in folder mp which is already
created.
Save the above code as “B.java” in folder sp. After that go to folder sp and compile at
command prompt as follows :
C:\>mp\cd sp
C:\>mp\sp>javac B.java
import mp.sp.*;
class pack_Hier
{
public static void main(String args[])
{
B b=new B();
b.displayB();
}
}
Above code saved as “pack_Hier.java” in drive where folder P is located.
compile as : C:\>javac pack_Hier.java
Run as : C:\>java pack_Hier
In the above program , we created sub package sp in the main package mp and
import them into “pack_Hier.java”
Sometimes we need to restrict the access of the variables and methods at outside of
the classes or packages. For this we use some keywords as modifiers before the
variables and methods. These are called “Access Modifiers or Access Specifiers” .
private protected :It is limited to that class and its sub class only.
………………………………………………………………………………………………………………………………………………………
Explain about usage of JAR( Java ARchive) in packages or in Execution of Java Programs.
A ) A JAR ( Java ARchive ) file is a special file format which is used to compress so many packages , .class
files , .. etc. into a single archive(collection) file.
It is similar to “. ZIP File “ but difference is (. zip ) files are first extracted and then used where as “ . jar
files “ are used and executed directly.
package p1 ;
import p2.*;
import p3.* ;
public class A
{
public static void main(String args [ ])
{
System.out.println(“From class A in pack p1”);
B.displayB( ) ;
C.displayC( ) ;
}
}
Note : methods declared as “static ‘ bcoz to access them with class name
package p2 ;
public class B
{
public static void display( )
{
System.out.println(“From class B in pack p2”);
}
}
package p3 ;
public class C
{
public static void display C ( )
{
System.out.println(“From class C in pack p3”);
}
}
a) Now create “ . jar file “ the above three packages and their class files at command prompt.
For this , we use special command “jar” as follows :
The above statement creates .jar file with p1 name. (as shown below :)
Now the “ p1.jar “ file compressed and contains all the ( . class files ) of three different packages
as single Executable file. (as shown above)
To see the advantage of a “.jar file” , delete all the packages(folders) p1,p2,p3 from the “Drive C : “ and
run the p1.jar file , then we will get output of all the deleted packages even they are deleted .
C : \ > java p1 . A
Note : Actually p1,p2,p3 folders are deleted but we can archive classes and get output from the
“. jar file “ , because the “p1.jar compress and contain all the classes into a single file .
This is main advantage of jar files.
……………………………………………………………………………………………………………………………………………………………………….
A) - API(Application Programming Interface ) document is a HTML( Hyper Text Markup Language ) file.
- It contains description of all the features of a software , a product or a technology.
- In Java , we can create these type of API documents for packages , classes .. etc . Then those API
documents contain description (information) about classes , variables, methods related to that package
- For Ex ,create a package “api_pack” which contains two classes Addition and Subtraction as follows :
package api_pack ;
package api_pack ;
Then different html files and other files are created in the folder “api_pack “ folder as shown below :
Among those files select “ index. html “ and open in any browser(iexplore,chrome etc) , then we will get
API document with for package “ api_pack “ as shown below : ( in exam,draw below table or below screenshot)
api_pack
class Addition
java.lang.object
Method summary
int sum(int x,int y) this method is used to find sum of given two integers
…………………………………………………………………………………………………………………………………………………………
Ans) Error : While developing a program , the programmer may make mistakesand
these mistakes are called “Errors”.
These errors are three types :
1. Compile-time ( Syntax ) Errors
2. Run-time Errors
3. Logical Errors
2. Run-Time Errors : These errors are found at execution time (Run time)of the
program. These Errors may raised because of following conditions :
Dividing an integer by zero.
Accessing an element that is out of the bounds of an array.
Trying to store a wrong data type value into an array etc.
Due to these Errors, we can’t get the desired output, or program may terminated etc.
3. Logical Errors : These errors raised because of errors in logic of the program.
The programmer might be using wrong formula or the design of the program itself
is wrong.
Here try , catch are the keywords and according to concept these are called
“Exception Handlers” ( Exception Handling statements/blocks ).
try block : In this block, we write the statements which may raises Exceptions.
If an Exception is raised, try block throws that Exception to “catch block”.
i.e. try block performs step1 and step2 of Exception Handling process.
catch block : This block receives an Exception thrown by “try block” , and wewrite
the statements to handle that Exception.
i.e. catch block performs step3 and step4 of Exception Handling process.
The following program shows the Exception Handling Process :
class ExHandle
{
public static void main( String args [ ] )
{
int a , b c;
a = 10 ;
b=5;
c=5;
try
{
int x = a / ( b – c ) ; /* raise ArithmeticException */
System.out.println(“ x value : “ + x ) ;
}
catch( ArithmeticException e )
{
System.out.println( “Division by zero is not possible “ ) ;
}
int y = a / ( b + c ) ;
System.out.println(“ y value : “ + y ) ;
}
}
Explanation : As shown above, the integer ‘a’ is dividing by zero (b-c=0).Generally it is
not possible , so it is Arithmetic Exception which leads to runtime error. This Exception is
raised in try block and throws into catch block. Then catch block display necessary
information and continue the execution of remaining code.
Then the output will be :
a) Checked Exceptions :
These should be handled in the code itself using try-catch blocks.
Multiple catch Statements : Sometimes there is need to handle more than one
Exception in the program, then we use more than one “catch” Statement(block).
finally statement :This is special statement block. It can receive any type of Exception.
The statements in this block are guaranteed to execute irrespective of Exception.
The following program shows the working of multiple catch and finally statements:
class ExHandle
{
public static void main( String args [ ] )
{
int a[ ] = { 10,5 } ;
int b = 5 ;try
{
int x = a[2] / ( b - a[1] ) ; /*raise ArrayOutOfBounds Exception */
System.out.println(“ x value : “ + x ) ;
}
catch( ArithmeticException e )
{
System.out.println( “Division by zero is not possible “ ) ;
}
catch( ArrayIndexOutOfBoundsException e )
{
System.out.println(“ You are accessing out of bound element“ ) ;
}
catch( ArrayStoreException e )
{
System.out.println( “ Wrong Datatype values stored” ) ;
}
finally
{
int y = a[1] / a[0] ;
System.out.println(“ y value = “ + y ) ;
}
}
}
Explanation: In the above program, we are accessing a[2](i.e. third element in Array)
but it is not exist because there are two elements in given array “a”. So when
Exception raised, the related catch block( 2 nd catch block) is executed and remaining
catch blocks are not executed.
Similarly , finally block is executed irrespective of exceptions.
……………………………………………………………………………………………………………
Q ) Explain about user defined Exceptions(our own Exceptions)
( or )
Explain about “ throw “ and “throws” clauses (statements).
In Java , it is possible to define our own Exceptions. The user defined Exceptions are
defined by extending the predefined class “Exception”.
throw : It is one of the Exception handler. It is used to throw (sent) the user defined
Exceptions.
The throw statement use the following syntax :
import java.lang.Exception ;
class myExcep extends Exception
{
myExcep(String msg)
{
super(msg);
}
}
class UDEx
{
public static void main(String args[ ])
{
int x , y ;
x=5;
y=1000;
float z = (float) x / (float) y ;
try
{
if (z<0.01)
throw new myExcep("Number is too small") ;
}
catch(myExcep e)
{
System.out.println(e.getMessage()) ;
}
finally
{
System.out.println("z value : "+z);
}
}
}
Explanation : In the above program, “myExcep” is user defined Exception.When z
value is less than 0.01, User Defined Exception is raised and it is caught by catch block.
Then object “e” contains the error message “ Number is too small ” and it is
displayed by method “getMessage()” .
throws : It is special keyword which is used with methods. It specifies that, themethod
might throw one or more Exceptions.
classReThrowEx
{
public void division()
{
int n1=30;
int n2=0;
try
{
int x=n1/n2;
System.out.println("x value "+x);
}
catch(ArithmeticException e)
{
throw e ; //Exception rethrow to catch block in main class
}
}
}
class oop22
{
public static void main(String[] args)
{
ReThrowEx r = new ReThrowEx();
try
{
r.division( ) ;
}
catch ( Exception e )
{
System.out.println(e.getMessage());
System.out.println("This Exception rethrown by division method and caught by main method");
}
}
}
output : / by zero
This Exception rethrown by division method and caught by main method
-----------------------------------------------------------------------------------------------------------
Unit - 3 Questions
2Q) Explain about final variables ,final methods, final classes and finalizer
4Q )Explain about Interfaces (or) Explain declaring, implementing and Extending of Interfaces.
11Q) Explain how to create API ( A pplication P rogramming I nterface ) Document in Java.