Unit - 5 Java Notes
Unit - 5 Java Notes
Inheritance in Java:
Inheritance is an important concept of OOPs. It is a mechanism in which a child object
acquires all the properties and behaviors of a parent object. Inheritance means driving a
new class from an existing class The existing class is known as base class or super class or
parent class. The new class is known as a derived class or sub class or child class.
Inheritance provides the reusability of code especially when there is a large scale of code to
reuse.
Note: we can’t access private members of class through inheritance.
Method overriding only possible through inheritance.
Syntax :
Class Superclass-name
{
//methods and fields
}
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
1.Single Inheritance:
➢ In single inheritance, subclasses inherit the features of one superclass. In the
image below, class A serves as a base class for the derived class B.
Output:
barking...
eating...
2.Multilevel Inheritance:
➢ In Multilevel Inheritance, a derived class will be inheriting a base class, and as
well as the derived class also acts as the base class for other classes. In the
below image, 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. In Java, a class cannot
directly access the grandparent’s members.
Or
➢ When there is a chain of inheritance, it is known as multilevel inheritance. As you
can see in the example given below, BabyDog class inherits the Dog class which
again inherits the Animal class, so there is a multilevel inheritance.
Multilevel Inheritance
Example:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
3. Hierarchical Inheritance:
➢ When two or more classes inherits a single class, it is known as hierarchical
inheritance. In the example given below, Dog and Cat classes inherits the
Animal class, so there is hierarchical inheritance. OR
➢ In Hierarchical Inheritance, one class serves as a superclass (base class) for more
than one subclass. In the below image, class A serves as a base class for the
derived classes B, C, and D.
Example:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
4. Multiple Inheritance (Through Interfaces)
In Multiple inheritances, one class can have more than one superclass and inherit
features from all parent classes. Please note that Java does not support multiple
inheritances with classes. In Java, we can achieve multiple inheritances only
through Interfaces. In the image below, Class C is derived from interfaces A
and B.
Q) Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have same method or different,
there will be compile time error.
Example:
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
Super Keyword
The super keyword in Java is a reference variable which is used to refer
immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is
created implicitly which is referred by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
Note: super() is added in each class constructor automatically by compiler if there is no super() or this().
As we know well that default constructor is provided by compiler automatically if there is no constructor.
But, it also adds super() as the first statement.
Another example of super keyword where super() is provided by the compiler implicitly.
class A
{
A()
{
System.out.println(" iam Class A");
}
}
class B extends A
{
B()
{
System.out.println(" i am Class B"); b// super and super()
}
public static void main(String[] args)
{
B ob=new B();
}
}
Output:
i am Class A
i am Class B
• If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
• In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.
class Main {
public static void main(String[] args) {
Person person = new Person(); // Create a Person object
person.display(); // Output: I am a person.
person.work(); // Output: Person is working.
Example:
Example:
abstract class Bike{
abstract void run(); // abstract method
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Output: running safely
Example2:
abstract class vehicle
{
abstract void start();
}
class car extends vehicle
{
void start()
{
System.out.println("Car Starts with key ");
}
}
class Scooter extends vehicle
{
void start()
{
System.out.println("Scooter Starts with kick ");
}
public static void main(String[] agrs)
{
//vehicle v = new vehicle();
car c = new car();
c.start();
Scooter s = new Scooter();
s. start();
}
}
Output:
For example:
Object obj=getObject(); //we don't know what object will be returned from this method
➢ The Object class provides some common behaviors to all the objects such as object
can be compared, object can be cloned, object can be notified etc.
• There are many built-in packages such as java, lang, awt, net, io, util, applet etc.
Import Package:
We import the java package using the keyword import.
Suppose we want to use the student class stored in the java.util package then we
can write the import statement at the beginning of the program like:
import.java.util.student;
1. Public
2. Private
3. Protected
4. Default
Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
Interface in Java:
Interface is just like a class in java.
▪An interface is a fully abstract class.
▪ It includes a group of abstract methods without a body.
▪ We use the interface keyword to create an interface in Java.
▪ Interface variables are by default public, static and final.
▪ Like abstract classes, we cannot create objects of interfaces.
▪ To use an interface, other classes must implement it.
▪ We use the implements keyword to implement an interface.
Inside the Interface, constructors are not allowed.
Inside the interface main method is not allowed.
On implementation of an interface, you must override all of its methods.
Syntax:
interface <interface_name>{
// declare methods that abstract
// declarepublic,final ,static fields
// by default.
}
Class Interface
In class, you can instantiate variables In an interface, you must initialize variables as
and create an object. they are final but you can’t create an object.
A class can contain concrete (with The interface cannot contain concrete (with
implementation) methods implementation) methods.
Example1:
interface Animal {
void animalSound(); // interface method (does not have a body)
void sleep(); // interface method (does not have a body)
}
class Pig implements Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
public void sleep() {
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig();
myPig.animalSound();
myPig.sleep();
}
}
Output:
The pig says: wee wee
Zzz
Notes on Interfaces:
Like abstract classes, interfaces cannot be used to create objects (in the example
above, it is not possible to create an "Animal" object in the MyMainClass)
Interface methods do not have a body - the body is provided by the "implement" class
On implementation of an interface, you must override all of its methods
Interface methods are by default abstract and public
Interface attributes are by default public, static and final
An interface cannot contain a constructor (as it cannot be used to create objects)
Exception:
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at
run time, that disturb the normal flow of the program.
OR In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
Exception Handling:
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the
normal flow of the application can be maintained. It is an event that disturbs the normal flow of the program.
It is an object which is thrown at runtime.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application. An exception
normally disturbs the normal flow of the application; that is why we need to handle exceptions
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Example:
class Test
{
public static void main (String[] agrs)
{
System.out.println(100);
System.out.println(10);
System.out.println(100);
System.out.println(10/0);//exception
System.out.println(20);
System.out.println(1000);
System.out.println(40);
System.out.println(1004);
System.out.println(4005);
System.out.println(6003);
}
}
Output:
100
10
100
Exception in thread "main" java.lang.ArithmeticException: / by zero
class Test
{
public static void main (String[] agrs)
{
System.out.println(100);
System.out.println(10);
System.out.println(100);
try{
System.out.println(10/0);
}
catch(Exception e)
{
System .out.println(“ We can’t divide by zero”);
}
System.out.println(20);
System.out.println(1000);
System.out.println(40);
System.out.println(1004);
System.out.println(4005);
System.out.println(6003);
}
}
The throwable class is the root class of Java Exception hierarchy inherited by two subclasses: Exception and
Error
Difference between Exception and Error in java:
Errors Exceptions
Error occurs because of lack of system resources Exception occurs because of your programs
Recovering from Error is not possible. We can recover from exceptions by either using try catch
block or throwing exceptions back to the caller.
Errors are mostly caused by the environment in Program itself is responsible for caused exceptions.
which program is running.
There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:
1) Checked Exception :
The classes that directly inherit the Throwable class except CompileException is known as checked
exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception :
The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
Exception:
class Test{
public static void main(String args[]){
//FileInputStream fis= new FileInputStream(“d:/abc.txt”);
//Class.forName(com.mysql.jdbc”);
int a=100,b=0;
int c=100/0;
System.out.println( c);
}
}
Output: compile successfully
JavaExceptionExample.java :
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero rest of the
code...
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code.
It means we can't use try block alone. The try block must be followed by either catch
or finally.
catch The "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.
finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur
an exception in the method. It doesn't throw an exception. It is always used with method
signature.
Java try-catch block :
Java try block is used to enclose the code that might throw an exception. It must be used within the
method.
If an exception occurs at the particular statement in the try block, the rest of the block code will not
execute.
Java try block must be followed by either catch or finally block.
try {
//code that may throw an exception
} catch(Exception_class_Name ref){}
try{
//code that may throw an exception
}finally{}
TryCatchExample2.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.
Example:
class MultipleCatchBlock1 {
try{
int a[]=new int[5];
a[5]=30/0;
// System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output: Arithmetic Exception occurs
rest of the code
In Java, using a try block inside another try block is permitted. It is called as nested try block.
Every statement that we enter a statement in try block, context of that exception is pushed onto
the stack.
For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException
while the outer try block can handle the ArithemeticException (division by zero).
Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
Throw Example:
if (balance <withdrawAmount) {
throw new InsufficientBalanceException("You have insufficient balance");
}
➢ When you declare a method using the Throws keyword, the method does not handle the
exception itself. But instead, it passes it on to the calling code. The calling code must either
handle the exception using a “try-catch” block or declare it in its own method signature
using the Throws keyword.
Throws Example:
public void withdraw(double amount) throws InsufficientBalanceException
InsufficientBalanceException("You have insufficient balance");
Note: If you don't handle the exception, before terminating the program, JVM executes finally
block (if any).
TestFinallyBlock.java
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of phe code...");
}
}
Output:
Built-in Exception:
Exceptions that are already available in Java libraries are referred to as built-in exception. These
exceptions are able to define the error situation so that we can understand the reason of getting this
error. It can be categorized into two broad categories, i.e., checked exceptions and unchecked
exception.
Checked Exception: Checked exceptions are called compile-time exceptions because these
exceptions are checked at compile-time by the compiler. The compiler ensures whether the
programmer handles the exception or not. The programmer should have to handle the exception;
otherwise, the system has shown a compilation error.
CheckedExceptionExample.java
import java.io.*;
class CheckedExceptionExample {
public static void main(String args[]) {
FileInputStream file_data = null;
file_data = new FileInputStream("C:/Users/ajeet/OneDrive/Desktop /Hello.txt");
int m;
while(( m = file_data.read() ) != -1) {
System.out.print((char)m);
}
file_data.close();
}
}
we are trying to read the Hello.txt file and display its data or content on the screen.
The program throws the following exceptions:
Output:
Unchec
ked Exceptions
The unchecked exceptions are just opposite to the checked exceptions. The compiler will not check
these exceptions at compile time. In simple words, if a program throws an unchecked exception, and
even if we didn't handle or declare it, the program would not give a compilation error. Usually, it
occurs when the user provides bad data during the interaction with the program.
Note: The RuntimeException class is able to resolve all the unchecked exceptions
UncheckedExceptionExample1.java
class UncheckedExceptionExample1 {
public static void main(String args[])
{
int postive = 35;
int zero = 0;
int result = positive/zero; //Give Unchecked Exception here.
System.out.println(result);
}
}
Output:
User-defined Exception:
In Java, we already have some built-in exception classes like
ArrayIndexOutOfBoundsException, NullPointerException, and ArithmeticException.
These exceptions are restricted to trigger on some predefined conditions.
In Java, we can write our own exception class by extends the Exception class. We can
throw our own exception on a particular condition using the throw keyword. For creating a
user-defined exception, we should have basic knowledge of the try-catch block and throw
keyword.
UserDefinedException.java
import java.util.*;
class UserDefinedException{
public static void main(String args[]){
try{
throw new NewException(5);
}
catch(NewException ex){
System.out.println(ex) ;
}
}
}
class NewException extends Exception{
int x;
NewException(int y) {
x=y;
}
public String toString(){
return ("Exception value = "+x) ;
}
}
Output:
Along with this, there are many differences between final, finally and finalize. A list of differences between
final, finally and finalize are given below:
Sr. Key final finally finalize
no.
final is the keyword finally is the block in Java finalize is the method in Java
and access modifier Exception Handling to which is used to perform
1. Definition which is used to apply execute the important code clean up processing just
restrictions on a class, whether the exception before object is garbage
method or variable. occurs or not. collected.
FinalExampleTest.java
In the above example, we have declared a variable final. Similarly, we can declare the methods and classes final
using the final keyword.
FinallyExample.java