0% found this document useful (0 votes)
28 views14 pages

Experiment No 4,5,6

Sppu SEIT Practical

Uploaded by

alleywills5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views14 pages

Experiment No 4,5,6

Sppu SEIT Practical

Uploaded by

alleywills5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Experiment No.

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.

Aim :- To Study Polymorphism using Java

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.

In Java polymorphism is mainly divided into two types:


 Compile time Polymorphism
 Runtime Polymorphism
1. Compile time polymorphism: It is also known as static polymorphism. This type of
polymorphism is achieved by function overloading or operator overloading.

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.

Example: By using different types of arguments


// Java program for Method overloading

class MultiplyFun {

// Method with 2 parameter


static int Multiply(int a, int b)
{
return a * b;
}

// Method with the same name but 2 double parameter


static double Multiply(double a, double b)
{
return a * b;
}
}

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 {

void operator(String str1, String str2)


{
String s = str1 + str2;
System.out.println("Concatinated String - "
+ s);
}

void operator(int a, int b)


{
int c = a + b;
System.out.println("Sum = " + c);
}
}

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

Runtime polymorphism: It is also known as Dynamic Method Dispatch. It is a process in which a


function call to the overridden method is resolved at Runtime. This type of polymorphism is
achieved by Method Overriding.

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.

Objectives :- 1) To understand the concept of Polymorphism using Java


2) To implement run time polymorphism

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 :-

abstract class shape {


abstract public void compute_area();
}
class rectangle extends shape {
public void compute_area() {
---
}
}
class triangle extends shape {
public void compute_area() {
---
}
}

public class Shapeclass {


public static void main(String[] args) {
---
}

Test case or Validation:


Different values for length and breadth of rectangle and base and height of triangle.

Result:- Area of Circle and area of Rectangle

Conclusion :- Thus studied the concept of Polymorphism using java.

Frequently asked Question


1. What is polymorphism and what are the types of it?
2. What is method overriding?
3. What is method overloading?
4. Difference between method overloading and overriding?
5. What is static and dynamic binding?
Experiment No. 5

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.

All the methods in an interface are abstract methods


1. An interface is a specification of method prototypes
2. An interface contains zero or more abstract methods
3. All the methods of interface are public, abstract by default
4. An interface may contain variables which are by default public static final
5. Once an interface is written any third party vendor can implement it
6. All the methods of the interface should be implemented in its implementation classes
7. If any one of the method is not implemented, then that implementation class should be
declared as abstract
8. We cannot create an object to an interface
9. We can create a reference variable to an interface
10. An interface cannot implement another interface
11. An interface can extend another interface
12. A class can implement multiple interfaces

Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}

1. Java Interface Example


In this example, the Printable interface has only one method, and its implementation is provided
in the A6 class.

interface printable{
void print();
}

class A6 implements printable{


public void print()
{
System.out.println("Hello");
}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

2. Write an example program for interface


Interface Shape
{
void area ();
void volume ();
double pi = 314;
}

class Circle implements Shape


{
double r;
Circle (double radius)
{r = radius; }
public void area ()
{
System.out.println ("Area of a circle is : " + pi*r*r );
}
public void volume ()
{
System.out.println ("Volume of a circle is : " + 2*pi*r);
}
}

class Rectangle implements Shape


{
double l,b;
Rectangle (double length, double breadth)
{
l = length; b = breadth;.
}
public void area ()
{
System.out.println ("Area of a Rectangle is : " + l*b );
}

public void volume ()


{
System.out.println ("Volume of a Rectangle is : " + 2*(l+b));
}
}

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 ();
}
}

Interface vs Abstract Class


An interface is like having a 100% Abstract Class. Interfaces cannot have non-abstract Methods
while abstract Classes can. A Class can implement more than one Interface while it can extend
only one Class. As abstract Classes come in the hierarchy of Classes, they can extend other
Classes while Interface can only extend Interfaces.
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known
as multiple inheritance.

Result:
Bicycle state:
speed: 2 gear: 2
Bike state:
speed: 1 gear: 1

Conclusion:

Thus, we have studies interface concept using java

Frequently asked Questions


1. Write a java interface which provides the implementation of Bank interface to
calculate Rate of Interest.
2. Write a Drawable interface has only one methoddraw(). Its implementation is
provided by Rectangle and Circle classes
3. A class implements an interface, but one interface extends another interface.
4. Create a vehicles as interface mention all common functionalities and create
classes like bicycle, car, bike implement all these functionalities in their own class
in their own way.
5. Create a animal class using interface and provide some common functionalities
and implement into some other classes.
6. Write a java interface which provides the implementation of Bank interface to
calculate Rate of Interest.
Experiment No. 6
Problem Statement:

Implement a program to handle Arithmetic exception, Array Index Out Of Bounds.


The user enters two numbers Num1 and Num2. The division of Num1 and Num2 is displayed. If
Num1 and Num2 were not integers, the program would throw a Number Format Exception. If
Num2 were zero, the program would throw an Arithmetic Exception. Display the exception.

Aim :
Exception handling

Theory

Exception handling in java with examples


Exception handling is one of the most important feature of java programming that allows us to
handle the runtime errors caused by exceptions. In this guide, we will learn what is an exception,
types of it, exception classes and how to handle exceptions in java with examples.

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.

Why an exception occurs?


There can be several reasons that can cause a program to throw exception. For example: Opening
a non-existing file in your program, Network connection problem, bad input data provided by
user etc.

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:

An exception generated by the system is given below


Exceptionin thread "main"java.lang.ArithmeticException:
/by zero at ExceptionDemo.main(ExceptionDemo.java:5)
ExceptionDemo:Theclass name
main :The method name
ExceptionDemo.java :The filename
java:5:Line number

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

There are two types of exceptions in Java:


1)Checked exceptions
2)Unchecked 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.

Syntax of try block


try{
//statements that may cause an exception
}

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.

Syntax of try catch in java

try
{
//statements that may cause an exception
}
catch(exception(type) e(object))
{
//error handling code
}

Example: try catch block

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.

Multiple catch blocks in Java


The example we seen above is having multiple catch blocks, lets see few rules about multiple
catch blocks with the help of examples. To read this in detail, see catching multiple exceptions 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.

Example of Multiple catch blocks


classExample2{
publicstaticvoid main(Stringargs[]){
try{
int a[]=newint[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
Output:
Warning: ArithmeticException
Out of try-catch block...

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.

Input: Values of Text field T1, T2


Output: Displays the result in Text field T3

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.

Frequently asked Questions


1. Design one login page and ask user to enter user id and password. If one
of the field is empty generate null pointer exception.
2. Write a method to process only text file , so we can provide caller with
appropriate error code when some other type of file is sent as input.
Write a bank class if user will provide account number which is greater than specified size then
method will produce array out of bound exception.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy