OOP Through Java Unit-3
OOP Through Java Unit-3
Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class.
Interfaces, creating the packages, using packages, importance of CLASSPATH and java.lang package.
Exception handling, importance of try, catch, throw, throws and finally block, user defined exceptions.
Inheritance
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)
Points to be remembered:
Inheritance is the most important and useful feature of OOP.
The existing class is known as parent class or base class or super class.
The new class is known as child class or derived class or sub class.
The Parent class is the class which provides features to another class.
The Child class is the class which receives features from another class.
It can be done by the extends keyword.
It follows IS-A relationship.
Uses / Advantages:
It allows us to reuse of code to improve the performance(Code Reusability).
For Method Overriding (to achieve runtime polymorphism).
Disadvantages:
Complicated.
Invoking methods creates overhead to the compiler.
Syntax:
class <ChildClassName> extends <ParentClassName>
{
//Implementation of child class
}
1
Types of Inheritance:
There are 3 types of inheritances in Java
Single inheritance
Multi-level inheritance
Hierarchical inheritance
Note:
Multiple inheritance and Hybrid inheritance can’t achieve directly but can achieve through
interface.
1.Single Inheritance:
It is a process of creating / deriving a class from single base class is known as Single Inheritance.
2.Multilevel inheritance:
It is a process of creating / deriving a class from already derived class is known as Multilevel
Inheritance.
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.
3
class MultiLevelInheritence{
Example
public static void main(String args[]){
class A{ C obj = new C();
int a=10; System.out.println(“C Class Variable=”+obj.c);
void dispa(){ obj.dispc();
System.out.println(“A Class”); System.out.println(“B Class Variable=”+ obj.b);
} obj.dispb();
class B extends A{ System.out.println(“A Class Variable=”+ obj.a);
int b=20; obj.dispa();
void dispb(){ }
System.out.println(“B Class”); }
} Output:
class C extends B{ C Class Variable=30
int c=30; C Class
B Class Variable=20
void dispc(){ B Class
System.out.println(“C Class”); A Class Variable=10
A Class
}
3.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.
Using B Class Object, we can’t access C class properties and D class properties.
Using C Class Object, we can’t access B class properties and D class properties.
4
Using D Class Object, we can’t access B class properties and C class properties.
Hybrid Inheritance
It is a combination of more than one type of inheritance
If the combination consists of multiple inheritance, not possible to implement
B C
× Invalid Valid
5
Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java.
(or)
Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
Imp Points:
Method overriding is used for runtime polymorphism.
Base class and Derived class should have the same method name (preference given to sub
class)
Both the methods should have same return type, scope and signature (no., order of
parameters & Type of parameters)
Private, Static and Final methods can’t be override.
Example:
class Parent{
void display()
{
System.out.println(“PARENT CLASS”);
}
}
class Child extends Parent{
void display()
{
super.display();
System.out.println(“CHILD CLASS”);
}
}
class Override
{
public static void main(String args[])
{
Child c = new Child();
c.display();
}}
Output:
PARENT CLASS
CHILD CLASS
6
Implementing the same thing with different ways i.e., Polymorphism
Super Keyword
The super keyword in java is a reference variable which is used to refer immediate parent class
object.
7
Example - 1:
class Parent
{
int a=40;
void display()
{
System.out.println(“PARENT CLASS”);
}
}
Output:
CHILD CLASS
30
40
PARENT CLASS
8
Final Keyword
In Java, the final keyword is used to denote constants. It can be used with variables, methods,
and classes. It is used to restrict a user in java.
Once any entity (variable, method or class) is declared final, it can be assigned only once. That is,
The final variable cannot be reinitialized with another value
The final method cannot be overridden
The final class cannot be extended
final variable: If a variable can be defined with final then that variable value cannot be changed
during the scope of program i.e., constant value.
Example-:
class Sample{
final int a=10;
Sample()
{
a=20;
}
}
class Test{
public static void main(String args[])
{
Sample obj=new Sample();
}
}
Output:
can’t assign a value to final variable a
final method: If a method can be defined with final then that method cannot be overridden
9
final class: If a class can be defined with final then that class cannot be inherited.
Example: class FinalTest{
public static void main(String args[]){
final class Parent{
void m1()
Child obj=new Child();
{
obj.m1();
System.out.println(“Parent Class”);
}
}
}
}
class Child extends Parent{
void m1(){ Output:
System.out.println(“Child Class”); cannot inherit from final Parent
}
}
Abstract Keyword
Abstraction in Java: Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
If a class contains complete definition for all methods then that is called concrete class
Abstract Method
10
Example:
abstract class A
{
Output:
abstract void display();
} Abstract Method in A
class B extends A{
void display()
{
System.out.println(“Abstract Method in A”);
}
}
class AbstractDemo{
public static void main(String args[]){
B b = new B();
b.display();
}
}
2 It is not possible to create object for abstract We can create object for concrete class
class
3 Abstract class contains abstract Concrete class contains only concrete methods
methods and concrete methods also but not abstract methods
4 Abstract class can’t be declared as final Concrete class can be declared as final
3 Every method present in abstract class need not Every method present in interface is by default
be public & abstract public & abstract
4 Every variable present in abstract class need not Every variable present in interface is always
be public, static & final public, static & final
Interfaces
• An interface in java is a blueprint of a class.
• Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body)
• An interface cannot be instantiated.
• To implement interface in a class, use implements keyword.
• A class can implement any number of interfaces.
• By default, each and every method in the interface is a public abstract.
• By default every variable in interface acts like public static final.
• We cannot create constructors in interface.
• We can use static method in interface.
• To declare an interface, use interface keyword
Advantages:
Interface is used to implement multiple inheritance in java.
It provides fully abstraction in java.
Syntax:
interface interface_name {
// declare fields // By default public static final
// declare methods // By default public abstract
}
Multiple Inheritance:
1)
implements
2)
implements extends
Example:
interface A{
int a=10;
void sum();
}
interface B{
int b=20;
}
class C implements A,B{
public void sum(){
System.out.println(“sum=”+(a+b))
}
}
class Test{
public static void main(String args[]){
C obj = new C();
obj.sum();
}
}
Output:
Sum=30
Packages
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two forms:
1. built-in package
2. user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
1) It provides code-reusablility.
2) It offers Modularity.
14
Simple example of java package
The package keyword is used to create a package in java.
//save as Test.java
package mypack;
public class Test
{
public void add( ) {
int a=20,b=40;
System.out.println("sum="+(a+b));
}
}
In this java file, specify the package name with the help of the package keyword.
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If we use package.* then all the classes and interfaces of this package will be accessible
but not subpackages.
import mypack.*;
class Main
{
public static void main(String[]args)
{
Test t=new Test();
t.add();
}}
15
Output:
Sum=60
2) Using packagename.classname:
import mypack.Test;
class Main
{
public static void main(String[]args)
{
Test t=new Test();
t.add();
}}
Output:
Sum=60
If we use fully qualified name then only declared class of this package will be accessible..
class Main{
public static void main(String[]args)
{
mypack.Test t=new mypack.Test();
t.add();
}}
Output:
Sum=60
Subpackage in java
Package inside the package is called the subpackage. It should be created to
categorize the package further.
16
Exception Handling
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
Try and catch blocks are interrelated i.e., without try we can’t use catch and vice versa.
Hierarchy of Java Exception classes:
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
17
Types of Java Exceptions:
There are mainly two types of exceptions:
1. Checked Exception
2. Unchecked Exception
1. Checked (Compile Time) Exception:
Checked exceptions are called compile-time exceptions because these exceptions are checked
at compile-time by the compiler.
Ex: IOException, SQLException etc...
2. Unchecked (Run Time)Exception:
Unchecked exceptions are not checked at compile-time, but they are checked at runtime
Ex: ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException,
NumberFormatException etc…
Keyword Description
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
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
Throw "throw" keyword is used to throw an exception implicitly or explicitly from a method or
any block of code.
18
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 raised when an input-output operation failed or interrupted
4. InterruptedException
It is raised when a thread is waiting, sleeping or doing some processing and it is interrupted
5. ArithmeticException
It is raised when an exception has occurred in an arithmetic operation such as division by zero.
6. ArrayIndexOutOfBoundsException
It is raised when 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
It 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
10. NoSuchMethodException
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 or greater than
the size ofthe string
19
Syntax:
Syntax:
try
try
{
{
//code that may throw an exception
//code that may throw an exception
}
}
finally
catch (Exception_class_Name ref)
{
{
// important code
// handle the exception
}
}
Example-1:
public class ExceptionHandlingDemo {
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Example-2:
public class ExceptionHandlingDemo1 {
public static void main(String[] args) {
int x,y;
int a=10,b=5,c=5;
try
{
x=a/(b-c);
System.out.println(x);
}
catch (ArithmeticException e)
{
System.out.println(“Division by Zero Error");
}
System.out.println("After Catch Block");
}
}
Output:
Division by zero error
After Try-Catch Block
20
Types of Unchecked (Run Time)Exceptions:
1. ArithmeticException divide by zero
2. NullPointerException sring str = null;
System.out.println(str.length()); ˟
3. NumberFormatException sring str = “hello”;
int num = Integer.ParseInt(str); ˟
4. ArrayIndexOutOfBoundsException int a[] = new int[5];
a[8] = 20; ˟
So, if you have to perform different tasks at the occurrence of different exceptions, use java
multi-catch block.
Points to remember:
o At a time only one exception occurs and at a time only one catch block is executed.
Example:
class multitrydemo
{
public static void main(String args[]) {
try
{
int a=10,b=5;
int c=a/b;
int d[]={0,1};
System.out.println(d[10]);
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(“Division by Zero error”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Index out of bound error”);
}}}
OUT-PUT:
Index out of bound error
After the catch statement
21
Usage of Java finally
In Java, the finally block is always executed no matter whether there is an exception or not.
The finally block is optional. And, for each try block, there can be only one finally block.
Syntax: Syntax:
try
try
{
{
//code that may throw an exception
//code that may throw an exception
}
}
catch (Exception_class_Name ref)
finally
{
{
// handle the exception
// important code
}
}
finally
{
// important code
}
22
Java throw keyword
(or)
User-defined Exception
The Java throw keyword is used to explicitly throw a single exception.
When we throw an exception, the flow of the program moves from the try block to
the catch block.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly
used to throw a custom exception.
Java provides us facility to create our own exceptions which are basically derived classes
of Exception class.
For example MyException in below code extends the Exception class.
Syntax
throw new exception_class("error message");
Example-1:
import java.lang.*;
class MyException extends Exception{
public MyException(String s){
// Call constructor of parent Exception
super(s);
}
}
class ThrowExcep
{
public static void main (String[] args) {
try
{
throw new ArithmeticException("My Own Exception");
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
}
}
Output:
My Own Exception
23
Java throws Keyword
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
Example-1:
class ThrowsDemo {
public static void main(String[] args)
{
Thread.sleep(10000);
System.out.println("Java Programming");
}
}
Output:
ThrowsDemo.java:4: error: unreported exception InterruptedException; must be caught or
declared to be thrown
Thread.sleep(10000);
Example – 2:
class ThrowsDemo {
public static void main(String[] args) throws InterruptedException
{
Thread.sleep(10000);
System.out.println("Java Programming");
}
}
Output:
Java Programming
24
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.
Advantage of Assertion:
It provides an effective way to detect and correct programming errors.
25