2. • Inheritance in java is a mechanism in which one object acquires all the
properties and behaviors of parent object.
• It is an important part of OOPs (Object Oriented programming system).
• The idea behind inheritance in java is that you can create new classes
that are built upon existing classes.
• When you inherit from an existing class, you can reuse methods and fields
of parent class.
• Moreover, you can add new methods and fields in your current class also.
• Inheritance represents the IS-A relationship, also known as parent-child
relationship.
Why use inheritance in java
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.
3. Terms used in Inheritence
• Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It
is also called a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
• Reusability:
– As the name specifies, reusability is a mechanism which facilitates you
to reuse the fields and methods of the existing class when you create
a new class.
– You can use the same fields and methods already defined in previous
class.
4. Syntax of Java Inheritance
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.
• In the terminology of Java, a class which is inherited is
called parent or super class and the new class is called
child or subclass.
5. Java Inheritance Example
• As displayed in the above figure, Programmer is the subclass and Employee
is the superclass.
• Relationship between two classes is Programmer IS-A Employee. It means
that Programmer is a type of Employee.
6. class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
OUTPUT
Programmer salary is:40000.0 Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
7. Types of inheritance in java
• On the basis of class, there can be three types of inheritance in java:
single, multilevel and hierarchical.
• In java programming, multiple and hybrid inheritance is supported
through interface only.
8. • When a class extends multiple classes i.e.
known as multiple inheritance. For Example:
9. Single Inheritance Example
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking... eating...
10. Multilevel Inheritance Example
File: TestInheritance2.java
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...
11. Hierarchical Inheritance Example
File: TestInheritance3.java
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...
12. 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 same method and you call it from
child class object, there will be ambiguity to call 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 now.
13. 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
Public Static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
14. Packages & Interfaces in Java
Introduction to Packages
• A package is a mechanism to group the similar type of classes, interfaces
and sub-packages and provide access control. It organizes classes into
single unit.
• In Java already many predefined packages are available, used while
programming.
• For example: java.lang, java.io, java.util etc.
Advantages of Packages
• Packages provide code reusability, because a package has group of classes.
• It helps in resolving naming collision when multiple packages have classes
with the same name.
• Package also provides the hiding of class facility. Thus other programs
cannot use the classes from hidden package.
• Access limitation can be applied with the help of packages.
• One package can be defined in another package.
15. Types of Packages
There are two types of packages available in Java.
1. Built-in packages
Built-in packages are already defined in java API. For
example: java.util, java.io, java,lang, java.awt, java.applet,
java.net, etc.
2. User defined packages
The package we create according to our need is called user
defined package.
16. Creating a Package
• We can create our own package by creating our own
classes and interfaces together.
• The package statement should be declared at the
beginning of the program.
• Syntax:
package <packagename>;
class ClassName
{
……..
……..
}
17. Example: Creating a Package
// Demo.java
package p1;
class Demo
{
public void m1()
{
System.out.println("Method m1..");
}
}
How to compile?
Syntax: javac –d directory javafilename
For Example: javac –d . Demo.java
How to run?
To run: java p1.Demo
18. Example: Program to create and use a user defined package in Java.
// Vehicle.java
package vehicles;
interface Vehicle
{
public void run();
public void speed();
}
//Bike.java
package vehicles;
public class Bike implements Vehicle
{
public void run()
{
System.out.println("Bike is running.");
}
public void speed()
{
System.out.println("Speed of Bike: 50 Km/h");
}
public static void main(String args[])
{
Bike bike = new Bike();
bike.run();
bike.speed();
}
}
19. Compile:
javac –d . Vehicle.java
javac –d . Bike.java
Run:
java vehicles.Bike
Output:
Bike is running
Speed of Bike: 50 Km/h
20. The “import” keyword
• The import keyword provides the access to other package
classes and interfaces in current packages.
• “import” keyword is used to import built-in and user
defined packages in java program.
• There are different 3 ways to access a package from other
packages.
1. Using full qualified name
Example
class Demo extends java.util.Scanner
{
//statements
}
21. 2. import only single class
Example
import java.util.Scanner;
class Demo
{
// statements
}
3. import all classes
Example
import java.util.*;
class Demo
{
// statements
}
22. Interface
• Interface is similar to a class, but it contains only abstract methods.
• By default the variables declared in an interface are public, static
and final.
• Interface is a mechanism to achieve full abstraction.
• An interface does not contain any constructor.
Syntax:
interface InterfaceName
{
public void method1();
public void method2();
<type> variableName = value;
}
23. Example: Sample of an interface
interface Employee
{
static final Id = 101;
static final String name = “ABC”;
void show();
void getSalary(double salary);
}
24. Extending interfaces
• An interface has to extend another interface as it happens
in class. It cannot implement another interface.
• Example: Sample program for extending interfaces
interface Base
{
public void display ();
}
interface Derive extends Base
{
public void show ();
}
25. Implementing interfaces
• A class implements an interface. After that, class can
perform the specific behavior on an interface.
• The implements keyword is used by class to implement an
interface.
Syntax:
class ClassName implements interfacename
{
// body of class
}
Note: A class can implement more than one interface. Java
can achieve multiple inheritances by using interface.
26. Example: Sample program to implements interface in Java
interface Results
{
final static float pi = 3.14f;
float areaOf(float l, float b);
}
class Rectangle implements Results
{
public float areaOf(float l, float b)
{
return (l * b);
}
}
class Square implements Results
{
public float areaOf(float l, float b)
{
return (l * l);
}
}
class Circle implements Results
{
public float areaOf(float r, float b)
{
return (pi * r * r);
}
}
public class InterfaceDemo
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Square square = new Square();
Circle circle = new Circle();
System.out.println("Area of Rectangle: "+rect.areaOf(20.3f, 28.7f));
System.out.println("Are of square: "+square.areaOf(10.0f, 10.0f));
System.out.println("Area of Circle: "+circle.areaOf(5.2f, 0));
}
}
Output:
Area of Rectangle: 582.61
Are of square: 100.0
Area of Circle: 84.905594
27. Example: Sample program to implements multiple inheritance
interface Vehicle
{
void run();
}
interface Bike extends Vehicle
{
void stop();
}
public class Demo implements Bike
{
public void run()
{
System.out.println("Vehicle is running.");
}
public void stop()
{
System.out.println("Bike is stop.");
}
public static void main(String args[])
{
Demo obj = new Demo();
obj.run();
obj.stop();
}
}
Output:
Vehicle is running.
Bike is stop.
28. Marker Interface
• An interface which does not contain any fields and
methods is known as marker or tag interface. It is an
empty interface.
For example Serializable, EventListener, MouseListner,
Remote, Cloneable etc.
Example:
package java.util;
public interface EventListner
{
}
29. Abstract class Interface
It cannot support multiple
inheritances.
Interface supports multiple
inheritances.
It contains both abstract and
non abstract method.
It contains only abstract
method.
Abstract class is the partially
implemented class.
Interface is fully
unimplemented class.
It can have main method and
constructor.
It cannot have main method
and constructor.
It can have static, non-static,
final, non-final variables.
It contains only static and final
variable.
Differences between Abstract class and Interface
30. Exception Handling in Java
• The exception handling in java is one of the
powerful mechanism to handle the runtime
errors so that normal flow of the application
can be maintained.
• Dictionary Meaning: Exception is an abnormal
condition.
• In java, exception is an event that disrupts the
normal flow of the program. It is an object
which is thrown at runtime.
31. What is exception handling
• Exception Handling is a mechanism to handle
runtime errors such as ClassNotFound, IO, SQL,
Remote etc.
Advantage of Exception Handling
• The core advantage of exception handling is to
maintain the normal flow of the application.
• Exception normally disrupts the normal flow of
the application that is why we use exception
handling
32. statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
• Suppose there is 10 statements in your program and there occurs an
exception at statement 5, rest of the code will not be executed i.e.
statement 6 to 10 will not run.
• If we perform exception handling, rest of the statement will be executed.
That is why we use exception handling in java.
34. 34
System Errors
System errors are thrown by JVM
and represented in the Error class.
The Error class describes internal
system errors. Such errors rarely
occur. If one does, there is little
you can do beyond notifying the
user and trying to terminate the
program gracefully.
37. Types of Exception
• There are mainly two types of exceptions:
checked and unchecked where error is
considered as unchecked exception. The sun
microsystem says there are three types of
exceptions:
– Checked Exception
– Unchecked Exception
– Error
38. Difference between checked and unchecked exceptions
1) Checked Exception
• The classes that extend Throwable class except RuntimeException
and Error are known as checked exceptions e.g.IOException,
SQLException etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
• The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are
not checked at compile-time rather they are checked at runtime.
3) Error
• Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError
etc.
39. 39
Trace a Program Execution
animation
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Suppose no exceptions in
the statements
40. 40
Trace a Program Execution
animation
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
The final block is always
executed
41. 41
Trace a Program Execution
animation
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Next statement in the
method is executed
42. 42
Trace a Program Execution
animation
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Suppose an exception of type
Exception1 is thrown in
statement2
43. 43
Trace a Program Execution
animation
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
The exception is handled.
44. 44
Trace a Program Execution
animation
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
The final block is always
executed.
45. 45
Trace a Program Execution
animation
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
The next statement in the
method is now executed.
46. 46
Trace a Program Execution
animation
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
statement2 throws an
exception of type Exception2.
48. 48
Trace a Program Execution
animation
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Execute the final block
49. 49
Trace a Program Execution
animation
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Rethrow the exception and
control is transferred to the
caller
50. Common scenarios where exceptions may occur
• There are given some scenarios where unchecked exceptions can occur. They
are as follows:
1) Scenario where ArithmeticException occurs
• If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
2) Scenario where NullPointerException occurs
• If we have null value in any variable, performing any operation by the variable
occurs an NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
3) Scenario where NumberFormatException occurs
• The wrong formatting of any value, may occur NumberFormatException.
Suppose I have a string variable that have characters, converting this variable
into digit will occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
51. 4) Scenario where
ArrayIndexOutOfBoundsException occurs
• If you are inserting any value in the wrong
index, it would result
ArrayIndexOutOfBoundsException as shown
below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
52. Java Exception Handling Keywords
• There are 5 keywords used in java exception
handling.
– try
– catch
– finally
– throw
– throws
53. Java try block
• Java try block is used to enclose the code that might throw an
exception. It must be used within the method.
• Java try block must be followed by either catch or finally block.
• Syntax of java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
• Syntax of try-finally block
try{
//code that may throw exception
• }finally{}
Java catch block
• Java catch block is used to handle the Exception. It must be used
after the try block only.
• You can use multiple catch block with a single try.
54. Problem without exception handling
public class Testtrycatch1{
public static void main(String args[]){
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
}
OUTPUT:
Exception in thread main
java.lang.ArithmeticException:/ by zero
55. Solution by exception handling
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/
by zero rest of the code...
57. • The JVM firstly checks whether the exception is
handled or not. If exception is not handled, JVM
provides a default exception handler that
performs the following tasks:
– Prints out exception description.
– Prints the stack trace (Hierarchy of methods where
the exception occurred).
– Causes the program to terminate.
• But if exception is handled by the application
programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
58. Java Multi catch block
• If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch
block.
• Let's see a simple example of java multi-catch block.
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}
System.out.println("rest of the code...");
}
}
Output:
task1 completed
rest of the code...
59. Why use nested try block
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:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
60. Java nested try example
Let's see a simple example of java nested try block.
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}
catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
61. Java finally block
• Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
• Java finally block is always executed whether exception is handled or not.
• Java finally block follows try or catch block.
java finally example where exception doesn't occur
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:
5
finally block is always executed
rest of the code...
62. java finally example where exception occurs and not handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:
finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero