Experiment No 4,5,6
Experiment No 4,5,6
4
Problem Statement:- Design a base class shape with two double type values and member
functions to input the data and compute_area() for calculating area of figure. Derive two classes’
triangle and rectangle. Make compute_area() as abstract function and redefine this function in the
derived class to suit their requirements. Write a program that accepts dimensions of
triangle/rectangle and display calculated area. Implement dynamic binding for given case study.
Theory:-
Polymorphism in Java
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
Real life example of polymorphism: A person at the same time can have different
characteristic. Like a man at the same time is a father, a husband, an employee. So the same
person posses different behaviour in different situations. This is called polymorphism.
Polymorphism is considered as one of the important features of Object Oriented Programming.
Polymorphism allows us to perform a single action in different ways. In other words,
polymorphism allows you to define one interface and have multiple implementations. The word
“poly” means many and “morphs” means forms, So it means many forms.
Method Overloading: When there are multiple functions with same name but different
parameters then these functions are said to be overloaded. Functions can be overloaded
by change in number of arguments or/and change in type of arguments.
class MultiplyFun {
class Main {
public static void main(String[] args)
{
System.out.println(MultiplyFun.Multiply(2, 4));
System.out.println(MultiplyFun.Multiply(5.5, 6.3));
}
}
Output:
8
34.65
Operator Overloading: Java also provide option to overload operators. For example, we can
make the operator (‘+’) for string class to concatenate two strings. We know that this is the
addition operator whose task is to add two operands. So a single operator ‘+’ when placed
between integer operands, adds them and when placed between string operands, concatenates
them.
In java, Only “+” operator can be overloaded:
To add integers
To concatenate strings
Example:
/ Java program for Operator overloading
class OperatorOVERDDN {
class Main {
public static void main(String[] args)
{
OperatorOVERDDN obj = new OperatorOVERDDN();
obj.operator(2, 3);
obj.operator("joe", "now");
}
}
Output:
Sum =5
Concatinated String -joenow
Method overriding, on the other hand, occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to be overridden.
Steps :
1. Start
2. Create an abstract class named shape that contains two double type numbers and an empty
method named compute_area().
3. Provide two classes named rectangle and triangle such that each one of the classes
extends the class Shape.
4. Each of the inherited class from shape class should provide the implementation for the method
compute_area().
5. Get the input and calculate the area of rectangle and triangle.
6. In the fourth separate class, create the objects for the two inherited classes and invoke the
methods and display the area values of the different shapes.
7. Stop.
Input:
length and breadth of rectangle
base and height of triangle
Output:
area of rectangle
area of circle
Implementation :-
Problem Statement:
Design and develop a context for given case study and implement an interface for Vehicles
Consider the example of vehicles like bicycle, car, and bike. All Vehicles have common
functionalities such as Gear Change, Speed up and apply breaks . Make an interface and put all
these common functionalities. Bicycle, Bike, Car classes should be implemented for all these
functionalities in their own class in their own way.
Aim :
To understand Interface in Java
Theory
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.A programmer uses an abstract class when there are some common features shared by all
the objects
.A programmer writes an interface when all the features have different implementations for
different objects Interfaces are written when the programmer wants to leave the implementation
to third party vendors An interface is a specification of method prototypes.
Syntax:
interface <interface_name>{
interface printable{
void print();
}
class InterfaceDemo
{
public static void main (String args[])
{
Circle ob1 = new Circle (102);
ob1.area ();
ob1.volume ();
Rectangle ob2 = new Rectangle (126, 2355);
ob2.area ();
ob2.volume ();
}
}
Result:
Bicycle state:
speed: 2 gear: 2
Bike state:
speed: 1 gear: 1
Conclusion:
Aim :
Exception handling
Theory
What is an exception?
An Exception is an unwanted event that interrupts the normal flow of the program. When an
exception occurs program execution gets terminated. In such cases we get a system generated
error message. The good thing about exceptions is that they can be handled in Java. By handling
the exceptions we can provide a meaningful message to the user about the issue rather than a
system generated message, which may not be understandable to a user.
Exception Handling
If an exception occurs, which has not been handled by programmer then program execution gets
terminated and a system generated error message is shown to the user. For example look at the
system generated exception below:
This message is not user friendly so a user will not be able to understand what went wrong. In
order to let them know the reason in simple language, we handle exceptions. We handle such
conditions and then prints a user-friendly warning message to user, which lets them correct the
error as most of the time exception occurs due to bad data provided by user.
Advantage of exception handling
Exception handling ensures that the flow of the program doesn’t break when an exception
occurs. For example, if a program has bunch of statements and an exception occurs mid way
after executing certain statements then the statements after the exception will not execute and the
program will terminate abruptly.
By handling we make sure that all the statements execute and the flow of program doesn’t break.
Difference between error and exception.Errors indicate that something severe enough has gone
wrong, the application should crash rather than try to handle the error.
Exceptions are events that occurs in the code. A programmer can handle such conditions and
take necessary corrective actions.
Few examples:
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when you try to divide a
number by zero this exception occurs because dividing a number by zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an array out of its
bounds, for example array size is 5 (which means it has five elements) and you are trying to
access the 10th element.
Types of exceptions
Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler
checks them during compilation to see whether the programmer has handled them or not. If these
exceptions are not handled/declared in the program, you will get compilation error. For example,
SQLException, IOException, ClassNotFoundException etc.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked
at compile-time so compiler does not check whether the programmer has handled them or not but
it’s the responsibility of the programmer to handle these exceptions and provide a safe exit.
For example,ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc.
Compiler will never force you to catch such exception or force you to declare it in the method
using throws keyword.
Try block
The try block contains set of statements where an exception can occur. A try block is always
followed by a catch block, which handles the exception that occurs in associated try block. A try
block must be followed by catch blocks or finally block or both.
While writing a program, if you think that certain statements in a program can throw a exception,
enclosed them in try block and handle that exception
Catch block
A catch block is where you handle the exceptions, this block must follow the try block. A single
try block can have several catch blocks associated with it. You can catch different exceptions in
different catch blocks. When an exception occurs in try block, the corresponding catch block that
handles that particular exception executes. For example if an arithmetic exception occurs in try
block then the statements enclosed in catch block for arithmetic exception executes.
try
{
//statements that may cause an exception
}
catch(exception(type) e(object))
{
//error handling code
}
If an exception occurs in try block then the control of execution is passed to the corresponding
catch block. A single try block can have multiple catch blocks associated with it, you should
place the catch blocks in such a way that the generic exception handler catch block is at the last
(see in the example below).
The generic exception handler can handle all the exceptions but you should place is at the end, if
you place it at the before all the catch blocks then it will display the generic message. You
always want to give the user a meaningful message for each type of exception rather then a
generic message.
classExamp
classExample1{
publicstaticvoid main(Stringargs[]){
int num1, num2;
try{
/* We suspect that this block of statement can throw
* exception so we handled it by placing these statements
* inside try and handled the exception in catch block
*/
num1 =0;
num2 =62/ num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch(ArithmeticException e){
/* This block will only execute if any Arithmetic exception
* occurs in try block
*/
System.out.println("You should not divide a number by zero");
}
catch(Exception e){
/* This is a generic Exception handler which means it can handle
* all the exceptions. This will execute if the exception is not
* handled by previous catch blocks.
*/
System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in Java.");
}
}
Output:
You should not divide a number by zero
I'm out of try-catch block in Java.
1. As mentioned above, a single try block can have any number of catch blocks.
2. A generic catch block can handle all the exceptions. Whether it is
ArrayIndexOutOfBoundsException or ArithmeticException or NullPointerException or any
other type of exception, this handles all of them. To see the examples of NullPointerException
and ArrayIndexOutOfBoundsException, refer this article: Exception Handling example
programs.
catch(Exception e)
{
//This catch block catches all the exceptions
}
If you are wondering why we need other catch handlers when we have a generic that can handle
all. This is because in generic exception handler you can display a message but you are not sure
for which type of exception it may trigger so it will display the same message for all the
exceptions
and user may not be able to understand which exception occurred. Thats the reason you should
place is at the end of all the specific exception catch blocks.
3. If no exception occurs in try block then the catch blocks are completely ignored.
4. Corresponding catch blocks execute for that specific type of exception:
catch(ArithmeticException e) is a catch block that can hanldeArithmeticException
catch(NullPointerException e) is a catch block that can handle
NullPointerException
5. You can also throw exception, which is an advanced topic and I have covered it in separate
tutorials: user defined exception, throws keyword, throw vs throws.
In the above example there are multiple catch blocks and these catch blocks executes
sequentially when an exception occurs in try block. Which means if you put the last catch block (
catch(Exception e)) at the first place, just after try block then in case of any exception this block
will execute as it can handle all exceptions. This catch block should be placed at the last to avoid
such situations.
Finally block
You should place those statements in finally blocks, that must execute whether exception occurs
or not.
Step1: Start.
Step2: Import java.awt package
Step3: Import java.lang.string,awt. event,applet.Applet packages.
Step4: Create Class
Step5: Create Buttons
and Text Fields. Step6:
Create the Data.
Step7: Perform
the division.
Step8: Print
the Data.
Step9: Stop.
Conclusion
Thus we have studies exception handling concept using java
Assignments
1. Write a java interface which provides the implementation of Bank interface to
calculate Rate of Interest.
2.The Drawable interface has only one method draw(). Its implementation is
provided by Rectangle and Circle classes.