UNIT-3 OOP Lecture Notes
UNIT-3 OOP Lecture Notes
❖ Interface
✓ An interface in Java is a blueprint of a class. It has static constants and
abstract methods.
✓ Interfaces can have abstract methods and variables. It cannot have a method
body.
✓ Java Interface also represents the IS-A relationship.
Why use Java interface?
There are mainly three reasons to use interface. They are
1. It is used to achieve total abstraction.
2. By interface, we can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling (means, that the classes are
independent of each other)
Note 1: Interfaces are used to implement abstraction. So, the question arises why
use interfaces when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas
variables in interface are final, public, and static.
How to declare an interface?
✓ An interface is declared by using the interface keyword.
✓ It provides total abstraction; means all the methods in an interface are
declared with the empty body, and all the fields are public, static, and final
by default.
Syntax:
Example:
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7(); Output:
13. obj.print();
14. obj.show(); Hello
15. } } Welcome
Example:
1. interface Printable{ // Single class can be able to implement
2. void print(); multiple Interfaces which are having same
3. }
method print(). And there is no ambiguity.
4. interface Showable{
5. void print();
6. }
Interface inheritance
✓ A class implements an interface, but one interface extends another interface.
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
✓ Since Java 8, we can have method body in interface. But we need to make it
default method.
Example:
1. interface Drawable{
2. void draw();
3. default void msg(){System.out.println("default method");}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8. class TestInterfaceDefault{
9. public static void main(String args[]){
10. Drawable d=new Rectangle();
11. d.draw();
12. d.msg();
13. } Output:
14.}
default method
drawing rectangle
❖ Java Packages
✓ A java package is a group of similar types of classes, interfaces, and sub-
packages.
✓ Package in java can be categorized in two form, built-in package, and user-
defined package.
✓ There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.
Advantage of Java Package
✓ Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
✓ Java package provides access protection.
✓ Java package removes naming collision.
Example: The package keyword is used to create a package in java.
1. //save as Simple.java
Output:
Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE Welcome to package 8
UNIT-3 – Object Oriented Programming
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package"); } }
Syntax to compile java package: javac -d directory javafilename
Eg: javac -d . Simple.java
✓ The -d is a switch that tells the compiler where to put the class file i.e. it
represents destination.
✓ The .(dot) represents the current folder.
Example:
1. //save by A.java
2. package pack;
3. public class A{
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A(); Output:
8. obj.msg();
9. } } Hello
2) Using packagename.classname
✓ If you import packagename.classname then only declared class of this
package will be accessible.
Example:
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){
5. System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4. class B{
5. public static void main(String args[]){ Output:
6. A obj = new A();
7. obj.msg(); Hello
8. } }
3) Using fully qualified name
✓ If you use fully qualified name, then only declared class of this package will
be accessible.
✓ Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class
Example:
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){
5. System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A(); //using fully qualified name
6. obj.msg();
7. } } Output:
Note: Hello
✓ If you import a package, all the classes and interface of that package will be
imported excluding the classes and interfaces of the subpackages.
✓ Hence, you need to import the subpackages as well.
❖ Subpackages in Java
✓ Package inside the package is called the subpackage.
✓ It should be created to categorize the package further.
✓ Sun Microsystem has defined a package named java that contains many
classes like System, String, Reader, Writer, Socket etc.
✓ These classes represent a group.
E.g., Reader and Writer classes are for Input/Output operation,
Socket and ServerSocket classes are for networking etc and so on.
✓ So, Sun has subcategorized the java package into subpackages such as
lang, net, io etc.
✓ And put the Input/Output related classes in io package, Server and
ServerSocket related classes in net packages and so on.
✓ The standard of defining package is domain.company.package.
E.g., com.lbrce.eee or org.sssit.dao.
Example:
1. package com.lbrce.eee;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. } } Output:
To Compile: javac -d . Simple.java Hello subpackage
To Run: java com.lbrce.eee Simple
❖ Exception Handling
Exception:
✓ An exception is an unwanted or unexpected event, which occurs during the
execution of a program i.e. at run time, that disrupts the normal flow of the
program’s instructions.
✓ Exception occurs in the code written by the developers.
✓ When executing Java code, different errors can occur.
➢ coding errors made by the programmer,
➢ errors due to wrong input, or other unforeseeable things.
✓ When an error occurs, Java will normally stop and generate an error
message.
✓ The technical term for this is: Java will throw an exception (throw an error).
✓ When an error is detected, an exception is thrown.
✓ Any exception that is thrown must be caught by the exception handler.
✓ If the programmer has forgotten to provide an exception handler, the
exception will be caught by the catch-all exception handler provided by the
system.
Advantages of Exceptions
✓ It separates error handling code from regular code.
✓ It could propagate error reporting up the call stack of methods.
✓ The grouping or categorizing of exceptions is a natural outcome of the class
hierarchy.
Example of Exception
1. import java.util.Scanner;
2. public class ExcptionExample
3. {
4. public static void main(String args[])
5. {
6. Scanner sc = new Scanner(System.in);
7. System.out.print("Enter a number: ");
8. int number = sc.nextInt();
9. System.out.println("You have entered: "+number);
10. } }
✓ Run the above program and enter a float value deliberately to generate an
exception.
Output:
Error Vs Exception:
✓ Error is an action that is inaccurate or incorrect according to syntax.
✓ It indicates a serious problem, that mainly occur due to the lack of system
resources. It cannot be caught or handled.
Exception Hierarchy
✓ All exception and errors types are sub classes of class Throwable, which is
base class of hierarchy.
✓ One branch is headed by Exception. This class is used for exceptional
conditions that user programs should catch. NullPointerException is an
example of such an exception.
✓ Another branch, Error are used by the Java run-time system(JVM) to
indicate errors having to do with the run-time environment itself (JRE).
StackOverflowError is an example of such an error.
Types of exceptions
✓ There are two types of exceptions in Java:
1) Checked exceptions :
✓ These are the exceptions that are checked at compile time.
✓ 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.
Example:
Consider the following Java program that opens the file at location “C:\test\a.txt”
and prints the first three lines of it.
The program does not compile, because the function main() uses FileReader() and
FileReader() throws a checked exception FileNotFoundException.
It also uses readLine() and close() methods, and these methods also throw checked
exception IOException.
import java.io.*;
class Example_checked {
public static void main(String[] args) {
// Reading file from path in local directory
FileReader file = new FileReader("C:\\test\\a.txt");
// Creating object as one of ways of taking input
BufferedReader fileInput = new BufferedReader(file);
// Printing first 3 lines of file "C:\test\a.txt"
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
// Closing file connections using close() method
fileInput.close();
} }
Output:
2) 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.
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:5)
Java Result: 1
Exception handling :
1) try block
✓ The try block contains set of statements where an exception can occur.
✓ While writing a program, if there are certain statements in a program can
throw an exception, enclosed them in try block and handle that exception.
Syntax of try block : try {
//statements that may cause an exception
}
2) 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.
catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block2");
}
}
catch(ArithmeticException e3){
System.out.print("Arithmetic Exception");
System.out.println(" handled in main try-block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" handled in main try-block");
}
}
}
Output:
ArrayIndexOutOfBoundsException handled in main try-block
✓ As you can see that the ArrayIndexOutOfBoundsException occurred in the
grandchild try-block3.
✓ Since try-block3 is not handling this exception, the control then gets
transferred to the parent try-block2 and looked for the catch handlers in try-
block2.
✓ Since the try-block2 is also not handling that exception, the control gets
transferred to the main (grandparent) try-block where it found the
appropriate catch block for exception.
✓ This is how the nesting structure works.
Observation:
If there an exception in try block 2 then execution of try block 3 is skipped and
corresponding catch block of try block 2 is executed and will get output as
Arithmetic Exception handled in try-block2.
Example 2 :
class Nest{
public static void main(String args[]){
//Parent try block
try{
//Child try block1
try{
System.out.println("Inside block1");
int b =45/0;
System.out.println(b);
}
catch(ArithmeticException e1){
System.out.println("Exception: e1");
}
//Child try block2
try{
System.out.println("Inside block2");
int b =45/0;
System.out.println(b);
}
catch(ArrayIndexOutOfBoundsException e2){
System.out.println("Exception: e2");
}
System.out.println("Just other statement");
}
catch(ArithmeticException e3){
System.out.println("Arithmetic Exception");
System.out.println("Inside parent try catch block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Inside parent try catch block");
}
System.out.println("Next statement...");
}
}
Output:
✓ The above example shows how the nested try block works. There are two
try-catch blocks inside main try block’s body. Marked them as block 1 and
block 2.
✓ Block 1: It divided an integer by zero and it caused an ArithmeticException,
since the catch of block1 is handling ArithmeticException "Exception: e1"
displayed.
✓ Block 2 : In block2, ArithmeticException occurred but block 2 catch is only
handling ArrayIndexOutOfBoundsException so in this case control jump to
the Main try-catch(parent) body and checks for the ArithmeticException
catch handler in parent catch blocks.
✓ Since catch of parent try block is handling this exception, the message
“Inside parent try catch block” displayed as output.
✓ Parent try Catch block: No exception occurred here so the “Next
statement...” displayed.
✓ The important point to note here is that whenever the child catch blocks are
not handling any exception, the jumps to the parent catch blocks, if the
exception is not handled there as well then the program will terminate
abruptly showing system generated message.
Finally block:
✓ A finally block contains all the crucial statements that must be executed
whether exception occurs or not.
✓ The statements present in this block will always execute regardless of
whether exception occurs in try block or not such as closing a connection,
stream etc.
Syntax of Finally block
try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}
Example:
class finally_exam
{
public static void main(String args[])
{
try
{
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBoundsException");
}
finally
{
System.out.println("finally block");
}
“throw” exception :
✓ In Java we have already defined exception classes such as
ArithmeticException, NullPointerException, ArrayIndexOutOfBounds
exception etc.
✓ These exceptions are set to trigger on different-2 conditions. For example
when we divide a number by zero, this triggers ArithmeticException, when
we try to access the array element out of its bounds then we get
ArrayIndexOutOfBoundsException.
✓ We can define our own set of conditions or rules and throw an exception
explicitly using throw keyword.
✓ For example, we can throw ArithmeticException when we divide number by
5, or any other numbers, what we need to do is just set the condition and
throw any exception using throw keyword. Throw keyword can also be used
for throwing custom exceptions,
Syntax :
throw new <exception_class>(“<error message>");
For example:
throw new ArithmeticException("dividing a number by 5 is not
allowed in this program");
Example:
Write a Java program, where we need to only register the students when their
age is less than 12 and weight is less than 40, if any of the condition is not met
then the user should raise an appropriate Exception with the warning message
“Student is not eligible for registration”.
Example:
import java.io.*;
class thr {
void sample() {
try {
System.out.println("Inside Sample()");
throw new NullPointerException("This is My data.."); }
catch(NullPointerException ne) {
System.out.println(ne); }
finally {
System.out.println("Close All...");
}}}
c lass thrw {
Public static void main(String args[])
{
thr t =new thr();
t.sample();
}}
Throws clause
✓ As we know that there are two types of exception checked and unchecked.
Checked exception (compile time force you to handle them, if you don’t
handle them then the program will not compile.
✓ On the other hand unchecked exception Runtime doesn’t get checked during
compilation.
✓ Throws keyword is used for handling checked exceptions . By using throws
we can declare multiple exceptions in one go.
using throws, we can declare multiple exceptions
public void myMethod()
{
try {
// Statements that might throw an exception
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}}
The code will become unnecessary long and will be less-readable
Assertion :
✓ Assertion is a statement in java. It can be used to test your assumptions
about the program.
✓ While executing assertion, it is believed to be true.
✓ If it fails, JVM will throw an error named AssertionError.
✓ It is mainly used for testing purpose.
Syntax of using Assertion:
There are two ways to use assertion.
First way is: assert expression;
Second way is: assert condition : expression;
Enable The Assertion :
To enable the assertion, -ea or -enableassertions switch of java must be used.
Compile : javac filename.java
Run it by: java -ea classname
Example :
import java.util.*;
class AssertionExample {
public static void main( String args[] ) {
Scanner s = new Scanner( System.in );
System.out.print("Enter ur age ");
System.out.println("value is "+value); } }
Assertion Examples:
1. Write a Java program to check a given integer is odd, if the given integer is
even must raise an AssertionError otherwise produce an appropriate
message as given integer is odd.
2. Write an Exception handling Program which include the Assert Statement in
try block and handle the raised exception from assert statement.
Where to use Assertions
• Arguments to private methods. Private arguments are provided by
developer’s code only and 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 user.
• Assertions should not be used on command line arguments.