RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
UNIT - 3
1. Define inheritance. Explain the different forms of inheritance with
example programs
The process by which one class acquires the properties i.e., variables,
methods, constructors, sub classes etc. from another class is called as
inheritance (base class -> derived class).
(Or)
It is a process of creating a new class from the existing class is known as
Inheritance.
Syntax:
class extends
,
//Implementation of child class
-
Types of Inheritance: There are 3 types of inheritances in Java
Single inheritance:
It is a process of creating / deriving a class from single base class is
known as Single Inheritance.
The class A serves as a base class for the derived class B
Example:
class A
,
int a=10;
void show()
,
[Link](a);
-
class B extends A
int b=20;
void display()
[Link](b);
-
void sum()
[Link](a+b);
class SingleInheritance
public static void main(String a*+)
B b = new B();
[Link]();
[Link]();
[Link]();
Output:
10 20 30
Multilevel inheritance: It is a process of creating / deriving a class from
already derived class is known as Multilevel
The class A serves as a base class for the derived class B, which in
turn serves as a base class for the derived class C.
C class can directly access the variables and methods of A, B and C.
Example:
class A
,
int a=10;
void dispa()
,
[Link](“A Class”);
-
class B extends A
,
int b=20;
void dispb()
,
[Link](“B Class”);
-
class C extends B
,
int c=30;
void dispc()
,
[Link](“C Class”);
-
class MultiLevelInheritence
,
public static void main(String args*+)
,
C obj = new C();
[Link](“C Class Variable=”+obj.c);
[Link]();
[Link](“B Class Variable=”+ obj.b);
[Link]();
[Link](“A Class Variable=”+ obj.a);
[Link]();
-
-
Output:
C Class Variable=30
C Class B Class Variable=20
B Class A Class Variable=10
A Class
Hierarchical Inheritance: It is a process of creating / deriving Multiple
classes from single base class is known as Hierarchical Inheritance.
The class A serves as a base class for the derived class B, C and D.
The class A serves as a base class for the derived class B, C and D.
Using C Class Object, we can’t access B class properties and D class
properties.
Using D Class Object, we can’t access B class properties and C class
properties.
Example:
class A
,
int a=10;
void dispa()
,
[Link](“Parent”);
-
class B extends A
,
int b=20;
void dispb()
,
[Link](“Child1”);
-
-
class C extends A
,
int c=30;
void dispc()
,
[Link](“Child2”);
-
-
class HierarchicalInheritence
,
public static void main(String args*+)
,
B obj1= new B();
C obj2 = new C();
[Link](“B Class Variable=”+obj1.b);
[Link]();
[Link](“A Class Variable=”+ obj1.a);
[Link]();
[Link](“C Class Variable=”+obj2.c);
[Link]();
[Link](“A Class Variable=”+ obj2.a);
[Link]();
-
-
Output:
B Class Variable=20
Child1
A Class Variable=10
Parent
C Class Variable=30
Child2
A Class Variable=10
Parent
2. Explain super keyword with all its usages. Support explanation with a
program
It can be used to access the variables, methods, constructors of base
class into derived class.
This will be used in derived class and the properties should be same in
both the classes.
By using super.(property name) ,the derived class can access the
properties of base class.
By default, constructor will be executed first
Example:
class Parent
,
int a=40;
void display()
,
[Link](“PARENT CLASS”);
-
-
Class Child extends Parent
,
int a=30;
void display()
,
[Link] (“CHILD CLASS”);
[Link] (a);
[Link](super.a);
[Link]();
-
-
class SuperDemo
,
public static void main(String args*+)
,
Child c = new Child();
[Link]();
-
-
Ouput:
CHILD CLASS
30
40
PARENT CLASS
3. Demonstrate the use of final keyword with suitable example.
In Java, the final keyword is used to denote constants. It can be used
with variables, methods, and classes.
Once any entity (variable, method or class) is declared final, it can be
assigned only once.
That is,
a. the final variable cannot be reinitialized with another value
b. the final method cannot be overridden
c. the final class cannot be extended
Example:
class FinalDemo
,
final int i=10;
void finalDemo()
,
i=i+10;
[Link](“Value of i: ”+i);
-
-
class FinalTest
,
public static void main(String args*+)
,
FinalDemo obj=new FinalDemo();
[Link]();
-
-
Output:
Error : can’t assign a value to final variable i
[Link] the differences between method overloading and
overriding.
[Link] between abstract class and interface
6. What is an abstract class? Can an abstract class have constructors?
Explain with example
A class which is declared with the abstract keyword is known as an
abstract class in Java.
It can have Variables, abstract and non-abstract methods (method
with the body).
If a method is declared with abstract keyword then it is called as
abstract method.
Implementation of abstract method can be written in derived class
only.
It can have constructors and static methods also.
It can have final methods which will force the subclass not to change
the body of the method.
Example:
abstract class A
,
int a;
A(int a)
,
this.a = a;
-
abstract int multiply(int val);
-
class B extends A
,
B()
,
super(2);
-
public int multiply(int val)
,
return this.a * val;
-
-
public class C
,
public static void main(String args*+)
,
B ob = new B();
[Link]([Link](3));
-
-
Output:
6
[Link] Interface? Demonstrate the use the interface concept with
suitable example.
Like a class, an interface can have methods and variables, but the
methods declared in an interface are by default public abstract (only
method signature, no body).
An interface cannot be instantiated, but we can create a reference for
interface.
To implement interface use implements keyword.
If the subclass is overriding all the methods of an interface then it is
called as implementation class.
A class can implement any number of interfaces
We cannot create constructors in interface.
By default every variable in interface acts like public static final.
To declare an interface, use interface keyword
Syntax:
interface interface_name
,
// declare variables
// By default public static final
int a=10;
// declare methods
// By default public abstract
-
Example:
interface Interface_Example
,
void test();
-
class Test implements Interface_Example
,
public void test()
,
[Link] ("Interface Method Implemented");
-
public static void main(String args*+)
,
Test p = new Test();
[Link]();
-
-
Output:
Interface Method Implemented
8. Explain how packages are created in Java. Write a program to
i) Construct a package with a class Test that performs addition of 2 integers.
ii) import that package and run
A java package is a group of similar types of sub-packages, classes
and interfaces.
Packages in java can be categorized in two form, built-in packages
and user-defined packages.
Java supports a keyword called “package” which is used to create
user-defined packages in Java programming.
To import java package into a class, we need to use java import
keyword which is used to access package and its classes into the java
program.
Syntax:
package package-name;
Example:
//Create a package
package pack1;
public class Test
,
static int a=10,b=20;
public static void add()
,
[Link](a+b);
-
-
//Save and compile the package
Javac -d [Link]
Importing that pack1
import [Link]; //importing pack1 package
public class Add
,
public static void main(String*+ args)
,
Test ob = new Test();
[Link]();
-
-
save and compile the program :
Javac [Link]
Run the program
Java Add
Output:
30
9. Explain about Exception Handling in Java in detail with suitable
examples.
Exception is an unwanted event that interrupts the normal flow of
the program (or) runtime error which will occurs during program
execution.
If any error occurred, the remaining code will not execute and
terminate the program abnormally.
Exception handling allows us to handle the runtime errors caused by
exceptions.
Used to raise an exception, handle an exception and avoiding
abnormal termination of a program.
We use 5 keywords in this i.e., try, catch, throw, throws, finally.
Exceptions are handled with the help of try and catch blocks.
Types of Java Exceptions:
There are mainly two types of exceptions:
checked and unchecked. There are three types of exceptions namely:
1. Checked Exception 2. Unchecked Exception 3. Error
o Checked Exception: The classes which directly inherit
Throwable class except Runtime Exception and Error are
known as checked exceptions. Checked exceptions are checked
at compile-time
o Unchecked Exception: The classes which inherit Runtime
Exception are known as unchecked exceptions. Unchecked
exceptions are not checked at compile-time, but they are
checked at runtime
o Error: Error is irrecoverable and it occurs due to problem with
computer & software.
Java Exception Keywords:
1. try: "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: "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: "finally" block is used to execute the important code of
the program It is executed whether an exception is handled or
not.
4. throw: "throw" keyword is used to throw an exception implicitly
or explicitly from a method or any block of code.
5. Throws: "throws" keyword is used to declare exceptions. It
doesn't throw an exception It specifies that there may occur an
exception in the method & always used with method signature.
Built-in exceptions:
1. ClassNotFoundException: This Exception is raised when we try
to access a class whose definition is not found.
2. FileNotFoundException: This Exception is raised when a file is
not accessible or does not open.
3. IOException: It is thrown when an input-output operation failed
or interrupted.
4. InterruptedException: It is thrown when a thread is waiting,
sleeping or doing some processing and it is interrupted.
5. ArithmeticException: It is thrown when an exceptional
condition has occurred in an arithmetic operation.
6. ArrayIndexOutOfBoundsException: It is thrown to indicate that
an array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of the array.
7. NullPointerException: This exception is raised when referring to
the members of a null object. Null represents nothing
8. NumberFormatException: This exception is raised when a
method could not convert a string into a numeric format.
9. NoSuchFieldException: It is thrown when a class does not
contain the field (or variable) specified.
[Link]: It is thrown when accessing a
method which is not found.
11. RuntimeException: This represents any exception which occurs
during runtime.
12. StringIndexOutOfBoundsException: It is thrown by String class
methods to indicate that an index is either negative than the size
of the string.
Java try-catch block:
1. "try" keyword is used to specify a block where we should place
exception code.
2. The try block must be followed by either catch or finally. It
means, we can't use try block alone.
3. Syntax:
try
,
//code that may throw an exception
-
catch (Exception_class_Name ref)
,
// handle the exception
-
Types of Unchecked (Run Time) Exceptions:
ArithmeticException -> divide by zero.
NullPointerException -> string str = null;
[Link]([Link]()); ˟
NumberFormatException -> string str = “hello”;
int num = [Link](str); ˟
ArrayIndexOutOfBoundsException -> int a*+ = new int*5+;
a*8+ = 20; ˟
Java Multi-catch block:
A try block can be followed by one or more catch blocks. Each
catch block must contain a different exception handler. So, if
you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
At a time only one exception occurs and at a time only one
catch block is executed.
All catch blocks must be ordered from most specific to most
general, i.e. catch for ArithmeticException must come before
catch for Exception.
Java Nested try Catch block:
In Java, using a try block inside another try block is permitted. It
is called as nested try block.
For example, the inner try block can be used to handle
ArithemeticException (division by zero) While the outer try
block can handle the ArrayIndexOutOfBoundsException.
Example:
public class NestedTry
,
public static void main(String*+ args)
,
try
,
int a*+=,10,0,30,40,50-;
try ,
int b=a*3+/a*1+;
-
catch(ArithmeticException e)
,
[Link](e);
-
a*5+=100;
-
catch(ArrayIndexOutOfBoundsException e)
,
[Link](e);
-
-
-
Output:
[Link]: / by zero
[Link]: Index 5 out of bounds for length 5
Usage of Java finally:
"finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not.
Syntax:
,
//code that may throw an exception
-
finally
,
// important code
-
Example:
public class FinallyDemo //code using try ,catch & finally
,
public static void main(String*+ args)
,
int x,y;
int a=10,b=5,c=5;
try
,
y=a/(b-c);
[Link](y);
-
catch(NullPointerException e)
,
[Link](e);
-
finally
,
[Link]("This is finally block");
-
-
-
Output:
This is finally block
Exception in thread "main" [Link]: / by zero
at [Link]([Link])
Java throw keyword:
The throw keyword in Java is used to implicitly or explicitly
throw an exception from a method or any block of code.
We can throw either checked or unchecked exceptions in Java
by throw keyword. It is mainly used to throw a custom
exception.
Syntax:
throw new exception_class("error message");
Java throws:
throws is a keyword in Java that is used in the declaration of a
method to indicate that this method might throw one of the
listed type exceptions.
The caller to these methods has to handle the exception using a
try-catch block.
Syntax:
type method_name(parameters) throws exception_list
Example: //code using throw & throws
public class ThrowThrowsExample
,
// Method that uses 'throws' to declare it can throw an ArithmeticException
public static void divide(int a, int b) throws ArithmeticException
,
if (b == 0)
,
// Using 'throw' to explicitly throw an ArithmeticException
throw new ArithmeticException("Division by zero is not allowed.");
-
else
,
[Link]("Result: " + (a / b));
-
-
public static void main(String*+ args)
,
try
,
// This will succeed
divide(10, 2);
// This will throw an exception
divide(10, 0);
-
catch (ArithmeticException e)
,
[Link]("Caught an exception: " + [Link]());
-
-
-
Output:
Result: 5
Caught an exception: Division by zero is not allowed.
10) What is user-defined custom Exception Explain it with suitable
example?
Java provides us facility to create our own exceptions which are
basically derived classes of Exception class.
Example:
class MyException extends Exception
,
public MyException(String s)
,
// Call constructor of parent Exception
super(s);
-
-
public class ThrowExcep
,
public static void main(String args*+)
,
try
,
throw new MyException("User defined exception");
-
catch (MyException ex)
,
[Link]("Exception Caught");
[Link]([Link]());
-
-
-
Output:
Caught User defined exception
11. Explain in detail about wrapper classes with examples
The wrapper class in Java provides the mechanism to convert
primitive into object and object into primitive.
autoboxing and unboxing feature convert primitives into objects and
objects into primitives automatically. The automatic conversion of
primitive into an object is known as
autoboxing and vice-versa unboxing.
Autoboxing: The automatic conversion of
primitive data type into its corresponding
wrapper class is known as autoboxing, for
example, byte to Byte, char to Character,
int to Integer, long to Long, float to Float,
boolean to Boolean, double to Double,
and short to Short.
Example:
public class WrapperDemo
,
public static void main(String args*+)
,
int a=100;
Integer obj1 = new Integer(a);
Integer i=[Link](a); //converting int into Integer explicitly
Integer j=a; //autoboxing
[Link](obj1+" "+i+" "+j);
-
-
Output:
100 100 100
12. What is Assertion and do you enable assertions in Java at runtime?
In Java, assertions are used as a debugging tool to check the
assumptions in your code. An assertion is a statement that you can
use to test your assumptions about your code during development. If
an assertion is false, it means there’s a bug in the code, and it throws
an AssertionError.
The assert statement is used with a Boolean expression and can be
written in two different ways.
First way:
assert expression;
Second way:
assert expression1 : expression2;
Example:
public class AssertExample
,
public static void main(String*+ args)
,
int number = -10;
// Simple assertion with condition
//assert number > 0;
// Checks if the number is greater than 0
assert number > 0:"number should not be negative"; [Link]("The
number is: " + number);
-
-
Output:
The number is: -10
After enabling assertions:
Output:
Exception in thread "main" [Link]: number should not be negative
Enabling Assertions:
By default, assertions are disabled. We need to run the code as
given. The syntax for enabling assertion statement in Java
source code is:
java –ea Test
(or)
java –enableassertions Test
Disabling Assertions:
The syntax for disabling assertions in java is:
java –da Test
(or)
java –disableassertions Test
Where to use Assertions:
Arguments to private methods. Private arguments are provided
by the developer’s code only and the developer may want to
check his/her assumptions about arguments.
Conditional cases.
Conditions at the beginning of any method.
Where not to use Assertions:
Assertions should not be used to replace error messages.
Assertions should not be used to check arguments in the public
methods as they may be provided by the user. Error handling
should be used to handle errors provided by users.
Assertions should not be used on command line arguments.