U3 Java
U3 Java
Q). Polymorphism
The word polymorphism is a combination of two words i.e. ploy and morphs. The word poly
means many and morphs means different forms. In short, a mechanism by which we can perform a
single action in different ways.
System.out.println (a+b) ;
Java compiler decides the data type of the result of the expression a+b depending on the data
types of a and b. If a and b are int type, then a + b will also be taken as int type. If a and b are float
type variables, then a+b will be taken as float type. If a is int and b is float, then the compiler
converts a also into float and then sum is found. Thus, the result a + b is exhibiting polymorphic
nature. It may exist as an int or as a float or as some other data type depending on the context.
This is also called 'Coercion'.
Types of Polymorphism
There are two types of polymorphism in Java:
1. Static Polymorphism (Compile Time Polymorphism)
2. Dynamic Polymorphism (Run Time Polymorphism)
1. Static Polymorphism:
The polymorphism exhibited at compilation time is called static polymorphism. Polymorphism that
is resolved during compiler time is known as static polymorphism. Method overloading is an
example of compile time polymorphism.
1. Method overloading :
The process of defining methods with same name but with different functionalities is termed
method overloading.
To create an overloaded method, several different method definitions are created in the class with
the same name but with different parameter lists. Java differentiates overloaded methods based
on the number and type of parameters and not on the return type of the method.
A compiler error would occur when two methods with the same name and same parameter list
but different return types are created.
class MethodOverload
{
public static void first()
{
System.out.println("without any arguments");
}
Output
2. Dynamic Polymorphism:
The polymorphism exhibited at runtime is called dynamic polymorphism. This means when a
method is called, the method call is bound to the method body at the time of running the
program, dynamically. In this case, Java compiler does not know which method is called at the
time of compilation. Only JVM knows at runtime which method is to be executed. Hence, this is
also called 'runtime polymorphism' or 'dynamic binding'.
1. Method Overriding:
Method overriding means both the super class method and sub class methods having the same
name, same signature. i.e., number of parameters and types of parameters should be same.
Method overriding is allowed only in inheritance. Method overriding is an example of
polymorphism.
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle
{
void run() //defining a method
{System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle
{
void run() //defining the same method as in the parent class
{System.out.println("Bike is running safely");}
public static void main(String args[])
{
Bike2 obj = new Bike2(); //creating object
obj.run(); //calling method
}
}
Output:
Bike is running safely
Bike is running safely
A static method is a method, one single copy in memory is shared by all the objects of the class. Static
methods belong to the class rather than to the objects. So they are also called class methods. When
static methods are overloaded or overridden, since they do not depend on the objects, the Java
compiler need not wait till the objects are created to understand which method is called.
Program: Write a program to use super class reference to call the calculate () method.
//static polymorphism
class One
{
static void calculate (double x)
{
system.out.println("square value="+(x*x));
}
}
class Two extends One
{
static void calculate (double x)
{
System.out.println("square root="+ Math.sqrt(x));
}
}
class Poly
{
public static void main(String args[])
{
one o= new Two ();
o.calculate (25);
}
}
Output:
Private methods are the methods which are declared by using the access specifier 'private. This
method is not to be available outside the class. So other programmers cannot access the private
methods.
Even private methods are not available in the sub_classes. This means there is no possibility to
override the private methods of the super_class in its sub_classes. So only method overloading is
possible in case of private methods.
Example:
class Hello
{
private void call ()
{
system.out.println (“Hello world!”);
}
public static void main (String args [])
{
Hello h1=new Hello();
h1.call ();
}
}
Here in this code we have a private method -call() and we try to access this method under the main
method which lies in the same class Hello. Hence we get the desired output.
But if you try to call this private method - call() in some other class then you won't get the desired
output. Because when you write a method as private then it's accessibility is limited to that
particular class only.
The Specifier final is used to finalize classes, methods and variables. Finalizing a thing effectively
'freezes the implementation or value of that thing. More specifically, here is how final works with
classes, variables and methods, respectively:
1. When the Specifier final is applied to a class, it means that the class cannot be inherited.
2. When final is applied to a variable, it means that the variable is constant.
3. When final is applied to a method in a class, it means that the method cannot be overridden in
the sub-classes. .
1. Finalizing classes:
In order to finalize a class, the Specifier final is added to the class definition. Typically, it is added
after protection Specifiers such as private (or) public. This is done as shown below:
2. Finalizing variables:
The value of a finalized variable cannot be changed. It is then, effectively, a constant. To declare
constants in Java, final variables with initial values are used. This declaration can be done in a
program as follows:
3. Finalizing methods:
Methods that cannot be overridden are known as finalized methods. The implementations of
final methods cannot be redefined in sub-classes. The syntax for declaring a method final is the
following.
It is possible to convert one primitive data type into another primitive data type. This is done in
two ways, widening and narrowing. The primitive data types are classified into two types, lower
types and higher types naturally, the lower types are the types which use less memory and which
can represent lesser number of digits in the value. The higher types use more memory and can
represent more number of digits. To recognize the lower and higher types, the following diagram
is useful:
Lower ------------------------------higher
Thus, char is a lower type than int. float is a higher type than long, boolean is not included earlier,
because it cannot be converted into any other type.
Converting a lower data type into a higher data type is called wide examples:
char ch = 'A' ;
Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science
Page no- 6
Here, we are converting char type variable 'ch' into used the cast operator by writing 'int' in the
simple. Now that ch is converted into int type, it can be is an example for widening.
int x=9500;
Here, we are converting int type variable 'x' into float. So, we wrote (float) before the variable x.
Widening is safe because there will not be any loss of data or precision or accuracy.
Converting a higher data type into a lower data type is called 'narrowing'. Take the examples:
int n=66;
Here, we are converting int type n value into char type. The value of n is 66 which is when
converted into char type represents the character 'B', since 66 is the ASCII value of 'B'. This
character is stored into ch.
The type_cast can be to its own class type or to one of its subclass or super_class types or
interfaces. There are compile-time rules and runtime rules for casting in java. There are two types
of Reference Type Casting in Java, they are:
1. Up Type_casting
2. Down Type_casting
1. Up Type_casting:
A subtype object into a supertype and this is called up Type_cast. In Java, we need not add an
explicit cast and you can assign the object directly. Compiler will understand and cast the value to
supertype. By doing this, we are lifting an object to a generic level. If we prefer, we can add an
2. Down Type_casting:
A supertype to a subtype is called down Type_cast. This is the mostly done cast. By doing this we
are telling the compiler that the value stored in the base object is of a super type. Then we are
asking the runtime to assign the value. Because of down Type_cast, we get access to methods of
the subtype on that object. When performing down Type_casting, that you’re well aware of the
type of object you’ll be casting.
Let's take an example, there is getObject () method that returns an object but it can be of any type
like Employee, Student etc, we can use Object class reference to refer that object. For example:
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.
Method Description
public final Class getClass() returns the Class class object of this object. The Class
class can further be used to get the metadata of this
class.
public int hashCode() returns the hashcode number for this object.
public boolean equals() compares the given object to this object.
protected Object clone() creates and returns the exact copy (clone) of this object.
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's
monitor.
public final void wait(long timeout) causes the current thread to wait for the specified
milliseconds, until another thread notifies (invokes
notify() or notifyAll() method).
protected void finalize() is invoked by the garbage collector before object is being
garbage collected.
An abstract method does not contain any body. It contains only the method header, So we can say it
is an incomplete method. An abstract class is a class that generally contains some abstract methods.
Both the abstract class and the abstract methods should be declared by using the key word 'abstract'.
Points to Remember
abstract class A
{
}
Abstract Methods:
A method which is declared as abstract and does not have implementation is known as an abstract
method.
abstract void printStatus(); //no method body and abstract
You have to place the abstract keyword before the method name in the method declaration.
An abstract method contains a method signature, but no method body. Instead of curly braces
an abstract method will have a semoi colon(;) at the end.
In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
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();
}
}
Interface in java
Interface in java
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
Defining Interface
An interface is like a fully abstract class, except that it cannot have any concrete method (or)
instance variables. It is a collection of abstract method declarations and constants that is static
final variables.
This means that interfaces do not specify any code to implement these methods.
Any class that implements an interface must implement all of the methods specified in that
interface.
A class can implement many interfaces but can extend only one class.
interface InterfaceName
{
variable declaration;
method declaration;
}
Here interface is a keyword and interfaceName is any valid Java variable.
Example:
interface Item
{
static final int code = 1001;
static final String name = "fan";
void display();
}
Extending Interfaces
Interfaces can also be extended as a classes. The new sub_interface will inherit all the members of
the super_interface in the manner similar to subclasses.
interface ItemConstants
{
int code = 1000;
String name = "Fan";
}
interface Item extends ItemConstants
{
void display();
}
Output:
While interfaces are allowed to extend to other interfaces, sub interfaces cannot define the
method declared in the super interface. Instead, it is the responsibility of any class that
implements the derived interface to define all the methods.
Interfaces can have access Specifiers of public or blank, just like classes.
An interface can be defined as extending another interface, similar to class hierarchy, but there is
no base interface analogous to the Object class.
import java.io.*;
interface inter1
{
int a = 100;
final static int b = 200;
}
interface inter2 extends inter1
{
void show();
}
class interclass implements inter2
{
public void show()
{
int c = a + b;
System.out.println("Sum="+c);
}
}
class ExtendingInterface
{
public static void main(String args[])
{
interclass obj = new interclass();
obj.show();
}
}
Output :
Implementing Interfaces
Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science
Page no- 12
Interfaces are used as "superclasses" whose properties are inherited by classes. It is, therefore,
necessary to create that inherits the given interface.
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.
Implementing Interface:
import java.io.*;
interface inter //interface define
{
void show();
}
class interclass implements inter // implement the interface
{
public void show()
{
System.out.println("Hello Java - Interface");
}
}
class ImplementingInterface
{
public static void main(String args[])
{
interclass obj = new interclass();
obj.show();
}
}
Output:
Java does not support multiple inheritances. This means that a class cannot extend more than one
class. Therefore, following is illegal
However, a class can implement one or more interfaces, which has helped Java get rid of the
impossibility of multiple inheritance. The extends keyword is used once, and the parent interfaces are
declared in a comma-separated list.
Example:
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A4 implements Printable, Showable
{
public void print()
{System.out.println("Hello");}
public void show()
{System.out.println("Welcome");}
Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
PACKAGES
Packages (Putting classes together)
If we need to use classes from other programs without physically copying them into the program
under development, this can be accomplished in java by using packages a concept similar to “class
libraries” in another languages.
1. Advantages of packages:
The classes contained in the packages of other programs can be easily reused.
Two classes in two different packages can have the same name. They can be uniquely
identified by packagename.classname.
Thus a Package is a collection of classes, interfaces and sub-packages. A Sub package in turns
divides into classes, interfaces and sub-sub-packages, etc.
Types of Packages:
In java the packages are classified into two categories. They are
User-defined packages are those packages that are designed (or) created by the developer
(user) to categorize classes and packages. They are much similar to the built-in that java
offers. It can be imported into other classes and used the same as we use built-in packages
Creating our own packages (or) user defined packages involves the following steps:
Step1:
1. To create a package, simply include a package command as the first statement in a Java
source file. First declare the name of the package using package keyword followed by a
package name.
2. This must be first statement in java source file (except any comment or white spaces).
3. Any class you declare within that file will belong to the specified package.
Step 2:
1. Next define the class that is to be put in the package and declare it as public.
package mypack; // package declaration
public class FirstClass // class definition
{
…………
………… // Body of class
…………
}
Step 3:
1. Now store the classname.java file as same as normal java programs save.
Step 4:
1. File is to be compiled as fallows.
Which creates FirstClass.class file and stores it in the mypack directory created under current
directory by -d. Java also supports the package hierarchy, which allows grouping related
classes into a package and then grouping related packages into a larger package. We can
achieve this by specifying multiple names in a package statement, separated by dot.
A java system package can be accessed either by using a fully qualified class name or by using
import statement. We generally use import statement.
Syntax:
Here pack1 is the top level package, pack2 is the package which is inside in pack1 and so on.
In this way we can have several packages in a package hierarchy. We should specify explicit
class name finally. Multiple import statements are valid. * indicates that the compiler should
search this entire package hierarchy when it encounters a class name.
It is also possible to write interfaces in a package. But whenever, we create an interface the
implementation classes are also should be created. We cannot create object to the interface
but we can create objects for implementation classes and use them. We write an interface to
display system date and time in the package mypack as shown in the following program.
package mypack;
public interface MyDate
{
void showDate();
}
Output:
C:\> javac -d. MyDate.java
C:\>
Compile the preceding code and observe that the Java compiler creates a sub directory with the
name mypack and stores MyDate.class file there. This MyDate.class file denotes the byte code of
the interface.
Program: Write a program to create an implementation class for the MyDate interface with the
name DateImpl and storing it in the same package mypack.
When the preceding code in completed, Datelmpl.class file is created in the same package mypack.
Datelmpl class contained showDate () method which can be called and used in any other program.
Program: Write a program which shows how to use the Datelmpl which is an implementation class
of MyDate interface.
import mypack.Datelmpl;
class DateDisplay
{
public static void main(String args[])
{
Datelmpl obj= new Datelmpl();
obj.showDate();
}
}
Output:
Here, we are creating pack2 which is created inside pack1. To use the classes and interfaces of pack2,
we can write import statement as:
This concept can be extended to create several sub packages. In the following program we are
creating tech package inside dream package by writing the statement
package dream.tech;
Program: Let us make a program to learn how to create a sub package in a package.
package dream.tech;
public class Sample
{
public void show ()
{
System.out.println ("welcome to Dream tech");
}
}
Output:
C:\>java -d. Sample.
C:\>
When the proceeding program is compiled, the Java compiler creates a sub directory with the name
dream. Inside this, there would be another sub directory with the name tech is created. In this tech
directory, Sample class is stored. Suppose the user wants to use the Sample class of dream.tech
import dream.tech.Sample;
Output:
The access specifiers in Java specify the accessibility (or) scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the
access Specifier on it.
1. Private:
The access level of a private specifier is only within the class. It cannot be accessed from
outside the class.
2. Default:
The access level of a default Specifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
3. Protected:
The access level of a protected Specifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.
4. Public:
The access level of a public Specifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
There are many non-access Specifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access Specifiers only.
Application Programming Interface (API) document is a Hyper Text Markup language (html) file that
contains description of all the features of software, a product or a technology.
API document is like a reference manual that is useful to all the users of the product to understand all
the features and how to use them. For example, JavaSoft people have created API document
separately for the three parts, Java SE, Java EE and Java ME after they created Java language.
Every feature of Java language is described in API document. We can select any package, any class in
that package and the description of the class along with the fields, constructors, methods will appear.
When we click on any of these features, a detailed description of the feature is displayed. We can also
click on Index of the first row to see the index of all items in alphabetical order. Let us know how to
create an API document for any software:
1. First of all, we should copy all the source code files (.java) into a directory. For example, copy
APIDocEx .java of the package pack into a directory
e:\temp.
2. We should open each of the source code files and provide Java documentation comments by
using /** and */. When documentation comments are written, the APIDocEx .java files look like
shown here:
}
Output
To create the document API, we need to use the javadoc tool as in the following.
javadoc M.java
After generating the documented API. We will now see many HTML(browser) files created. Now we
need to open the index.html file to get the information about the classes. The figure below shows the
following.
JAR (Java Archive) file is a file that contains compressed version of class files, audio files, image files
or directories. We can imagine a jar file as a zipped file (.zip) that is created by using WinZip software.
Even, WinZip software can be used to extract the contents of a jar file. The difference is that a jar file
can be used as it but whereas the .zip file cannot be used directly. The files should be extracted first
from a .zip file, and then used...
Exceptions Handling
Error
It is common to make mistakes while developing as well as typing a program. A mistake leads to an
error. Errors are the wrongs that can make a program go wrong.
An error may produce an incorrect output (or) may terminate the execution of the program
abruptly (o)r even may cause the system to crash. It is therefore important to detect and manage
properly all the possible error condition in the program so that the program will not terminate or
crash during execution.
Types of Errors
Errors may broadly classified into two categories.
1. Compile-time errors
2. Run-time errors.
1. Compile-Time Errors
All syntax errors will be detected and displayed by the java compiler and therefore these errors
are known as compile-time errors. Whenever the compiler displays an error, it will not create the
.class file.
Most of the compile time errors are due to typing mistakes. The most common problems:
Missing semicolons
Missing brackets in the classes and methods
Misspelling of identifiers and keywords
Missing of double quotes in strings
Use of undeclared variables
Incompatible types in assignment / initialization And so on
2. Runtime Errors
Sometimes, a program may compile successfully creating the .class file but may not run properly.
Such programs may produce wrong results due to wrong logic (or) may terminate due to errors
such as stack overflow. Most common Run-time errors are:
Dividing an integer by zero
Accessing an element that is out of the bounds of an array
Trying to store a value into an array of an incompatible class or type
Passing a parameter that is not in a valid range or value for a method
Attempting to use a negative size of an array.
Converting invalid string to a number
Accessing a character that is out of bounds of a string
When such errors encountered, java typically generates an error message an aborts the program.
The following program is the illustration of Run-time errors.
Exception
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 (i.e. informs us that an error has occurred).
If the exception object is not caught and handled properly, the interpreter will display an
error message and will terminate the program.
If we want the program to continue with exception of the remaining code, then we should
try to catch the exception object thrown by the error condition and then display an
appropriate message for taking corrective actions. This task is known as Exception Handling.
The purpose of exception handling mechanism is to provide a means to detect and report an
“Exceptional Circumstance” so that appropriate action can be taken.
Exception handling mechanism performs the following tasks:
Find the problem ( Hit the exception)
Inform that an error has occurred (throw the exception)
Receive the error information (catch the exception)
Take corrective actions (Handle exception)
The error handling mechanism code basically consists of two segments, one detect errors and to
throw exceptions and other to catch exceptions and to take appropriate actions.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5; //exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in your program and there occurs an exception at statement 5,
the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform
exception handling, the rest of the statement will be executed. That is why we use exception
handling in Java.
Java exception handling is managed via 5 keywords, try, catch, throw, throws and finally. The
general form of exception handling block is
1. Try:
The "try" keyword is used to specify a block where we should place exception code. The try
block must be followed by either catch (or) finally. It means, we can't use try block alone.
2. Catch:
The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
3. Finally:
The "finally" block is used to execute the important code of the program. It is executed
whether an exception is handled or not.
4. Throw:
5. Throws:
The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies
that there may occur an exception in the method. It is always used with method signature.
Java uses the keywords try and catch to handles the exceptions in the java programs.
The following table shows the some common errors that are occurred in the java programs.
These exceptions are not essentially handled in the program code, instead the JVM handles
such exceptions. Unchecked exceptions are extended from the class
java.lang.RuntimeException.
Syntax:
try
{
//Statements that causes Exception
}
catch(ExceptionType ex_ob)
{
//Statements that handle Exception
}
Example:
Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science
Page no- 28
Example:
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}
catch(Exception e)
{System.out.println("common task completed");}
System.out.println("rest of the code...");
} }
Output: task1 completed
rest of the code...
Finally Statement
finally creates a block of code that will be executed after a try/catch block has completed. The finally
block will execute whether or not an exception is thrown. If an exception is thrown, the finally block
will execute even if no catch statement matches the exception. It may be added immediately after the
try block or after the last catch block.
Syntax 1:
try
{
// statements
}
finally
{
// statements
}
Syntax 2:
try
{
// statements
}
catch (…………)
{
// statements
}
catch (…………)
{
// statements
}
finally
{
// statements
}
In case the programmer does not want to handle the checked exceptions, he should throw them out
using throws clause. Otherwise, there will be an error flagged by Java complier.
package demo;
import java.io.*;
public class Demo
{
void checkout() throws IOException
{
System.out.println("checking machine");
}
public static void main(String[] args) throws IOException
{
Demo d = new Demo();
d.checkout();
System.out.println("successfully checked");
}
}
In the above statement, Null Pointer Exception class object is created and 'Exception data' is stored
into its object. Then it is thrown using throw statement. Now, we can catch it using catch block as:
//using throw
class Sample
{
static void demo()
{
try
{
System.out.println(“inseid demo()”);
throw new NullPointerException(“Excception data”);
}
catch(NullPointerException)
{
System.out.println()ne;
}
}
class ThrowDemo
{
public static void main(String args[])
{
Sample.demo();
}
}
class B
{
public static void main (String args[])
{
A a= new A();
try {
a.methodl ()
}
catch(StringIndexOutOfBoundsException sie)
{
System.out.println ("I caught rethrown exception");
}
}
}
Output: