Module I - Basic Java 2
Module I - Basic Java 2
CSE
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors
of parent object.
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, and you can add new methods and fields also.
}
The extends keyword indicates that you are making a new class that derives from an existing
class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called
a subclass.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A [Link] means that Programmer is a
type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
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.
single,
multilevel
hierarchical.
Note: Multiple inheritance is not supported in java through [Link] a class extends multiple
classes i.e. known as multiple inheritance.
void msg(){[Link]("Hello");}
class B{
void msg(){[Link]("Welcome");}
C obj=new C();
Test it Now
class Vehicle{
[Link]();
Test it Now
Output:Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass that is
why we use method overriding.
In this example, we have defined the run method in the subclass as defined in the parent class but
it has some specific implementation. The name and parameter of the method is same and there is
IS-A relationship between the classes, so there is method overriding.
class Vehicle{
[Link]();
Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of
interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%,
7% and 9% rate of interest.
class Bank{
class Test2{
Output:
Static method is bound with class whereas instance method is bound with object. Static belongs
to class area and instance belongs to heap area.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user. Another way, it shows only important things to the user and hides the internal details
for example sending sms, you just type the text and send the message. You don't know the
internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.
In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
[Link]();
Test it Now
running safely..
In this example, Shape is the abstract class, its implementation is provided by the Rectangle and
Circle classes. Mostly, we don't know about the implementation class (i.e. hidden to the end
user) and object of the implementation class is provided by the factory method.
A factory method is the method that returns the instance of the class. We will learn about the
factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class
will be invoked.
File: [Link]
//In real scenario, implementation is provided by others i.e. unknown by end user
class TestAbstraction1{
Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape()
method
[Link]();
Test it Now
drawing circle
File: [Link]
class TestBank{
Bank b;
b=new SBI();
b=new PNB();
}}
Test it Now
An abstract class can have data member, abstract method, method body, constructor and even
main() method.
Bike(){[Link]("bike is created");}
class TestAbstraction2{
[Link]();
[Link]();
Test it Now
bike is created
running safely..
gear changed
Rule: If there is any abstract method in a class, that class must be abstract.
class Bike12{
Test it Now
Rule: If you are extending any abstract class that have abstract method, you must either provide t
The abstract class can also be used to provide some implementation of the interface. In such
case, the end user may not be forced to override all the methods of the interface.
Note: If you are beginner to java, learn interface first and skip this example.
interface A{
void a();
void b();
void c();
void d();
class M extends B{
class Test5{
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Test it Now
Output:I am a
I am b
I am c
I am d
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and
multiple inheritance in Java.
There are mainly three reasons to use interface. They are given below.
interface
In other words, Interface fields are public, static and final bydefault, and methods are
public and abstract.
Simple example of Java interface
In this example, Printable interface have only one method, its implementation is provided in the
A class.
interface printable{
void print();
[Link]();
Test it Now
Output:Hello
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.
interface Printable{
void print();
interface Showable{
void show();
[Link]();
[Link]();
Test it Now
Output:Hello
Welcome
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of
class. But it is supported in case of interface because there is no ambiguity as implementation is
provided by the implementation class. For example:
interface Printable{
void print();
interface Showable{
void print();
[Link]();
Test it Now
Hello
As you can see in the above example, Printable and Showable interface have same methods but
its implementation is provided by class TestTnterface1, so there is no ambiguity.
Interface inheritance
interface Printable{
void print();
void show();
[Link]();
[Link]();
Test it Now
Hello
Welcome
An interface that have no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information to the
JVM so that JVM may perform some useful operation.
Note: An interface can have another interface i.e. known as nested interface. We will learn it in
detail in the nested classes chapter. For example:
interface printable{
void print();
An interface i.e. declared within another interface or class is known as nested interface. The
nested interfaces are used to group related interfaces so that they can be easy to maintain. The
nested interface must be referred by the outer interface or class. It can't be accessed directly.
There are given some points that should be remembered by the java programmer.
Nested interface must be public if it is declared inside the interface but it can have any access
modifier if declared within the class.
interface interface_name{
... }
class class_name{
... }
In this example, we are going to learn how to declare the nested interface and how we can access
it.
interface Showable{
void show();
interface Message{
void msg();
[Link]();
Test it Now
As you can see in the above example, we are acessing the Message interface by its outer
interface Showable because it cannot be accessed directly. It is just like almirah inside the room,
we cannot access the almirah directly because we must enter the room first. In collection
frameword, sun microsystem has provided a nested interface Entry. Entry is the subinterface of
Map i.e. accessed by [Link].
Internal code generated by the java compiler for nested interface Message
The java compiler internally creates public and static interface as displayed below:.
Let's see how can we define an interface inside the class and how can we access it.
class A{
interface Message{
void msg();
[Link]();
Test it Now
interface M{
class A{}
void msg();
Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
Let's see a simple example where we are using interface and abstract class both.
<a href="#">interface</a> A{
void b();
void c();
void d();
//Creating abstract class that provides the implementation of one method of A interface
//Creating subclass of abstract class, now we need to provide the implementation of rest of the
methods
class M extends B{
class Test5{
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Test it Now
Output:
I am a
I am b
I am c
I am d
Java Package
Package class
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.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
package in java
//save as [Link]
package mypack;
[Link]("Welcome to package");
If you are not using any IDE, you need to follow the syntax given below:
For example
javac -d . [Link]
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. [Link] etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it representsdestination.
The . represents the current folder.
There are three ways to access the package from outside the package.
import package.*;
import [Link];
fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
//save by [Link]
package pack;
public class A{
//save by [Link]
package mypack;
import pack.*;
class B{
[Link]();
Output:Hello
2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.
//save by [Link]
package pack;
public class A{
//save by [Link]
package mypack;
import pack.A;
class B{
[Link]();
Output:Hello
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 or interface.
It is generally used when two packages have same class name e.g. [Link] and [Link] packages
contain Date class.
//save by [Link]
package pack;
public class A{
//save by [Link]
package mypack;
class B{
[Link]();
Output: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 subpackage as well.
Note: Sequence of the program must be package then import then class.
sequence of package
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Let's take an example, Sun Microsystem has definded a package named java that contains many
classes like System, String, Reader, Writer, Socket etc. These classes represent a particular 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 classes in net packages and so on.
Example of Subpackage
package [Link];
class Simple{
[Link]("Hello subpackage");
Output:Hello subpackage
There is a scenario, I want to put the class file of [Link] source file in classes folder of c: drive.
For example:
//save as [Link]
package mypack;
[Link]("Welcome to package");
To Compile:
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the
class file resides.
The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of java that tells
were to look for class file. For example:
Output:Welcome to package
There are two ways to load the class files temporary and permanent.
Temporary
Permanent
Rule: There can be only one public class in a java source file and it must be saved by the public
class name.
class A{}
class B{}
If you want to put two public classes in a package, have two java source files containing one
public class, but keep the package name same. For example:
//save as [Link]
package javatpoint;
//save as [Link]
package javatpoint;
Package class
The package class provides methods to get information about the specification and
implementation of a package. It provides methods such as getName(), getImplementationTitle(),
getImplementationVendor(), getImplementationVersion() etc.
Example of Package class
In this example, we are printing the details of [Link] package by invoking the methods of
package class.
class PackageInfo{
Package p=[Link]("[Link]");
IS sealed: false
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.
In this page, we will learn about java exception, its type and the difference between checked and
unchecked exceptions.
What is exception
In java, exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL,
Remote etc.
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. Let's take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
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.
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
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions [Link], 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
There are given some scenarios where unchecked exceptions can occur. They are as follows:
int a=50/0;//ArithmeticException
If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
String s=null;
[Link]([Link]());//NullPointerException
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=[Link](s);//NumberFormatException
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
a[10]=50; //ArrayIndexOutOfBoundsException
try
catch
finally
throw
throws
Java try-catch
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
try{
}catch(Exception_class_Name ref){}
try{
}finally{}
Java catch block is used to handle the Exception. It must be used after the try block only.
Test it Now
Output:
As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be
executed.
try{
int data=50/0;
}catch(ArithmeticException e){[Link](e);}
Test it Now
Output:
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
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 the stack trace (Hierarchy of methods where the exception occurred).
But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.
try{
a[5]=30/0;
Test it Now
Output:task1 completed
Rule: At a time only one Exception is occured and at a time only one catch block is executed.
Rule: All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception .
class TestMultipleCatchBlock1{
try{
a[5]=30/0;
Test it Now
Output:
Compile-time error
The try block within a try block is known as nested try block in java.
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)
class Excep6{
try{
try{
[Link]("going to divide");
int b =39/0;
}catch(ArithmeticException e){[Link](e);}
try{
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){[Link](e);}
[Link]("other statement);
}catch(Exception e){[Link]("handeled");}
[Link]("normal flow..");
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Note: If you don't handle exception, before terminating the program, JVM executes finally
block(if any).
Finally block in java can be used to put "cleanup" code such as closing a file, closing connection
etc.
Case 1
class TestFinallyBlock{
try{
int data=25/5;
[Link](data);
catch(NullPointerException e){[Link](e);}
Test it Now
Output:5
Case 2
class TestFinallyBlock1{
try{
int data=25/0;
[Link](data);
catch(NullPointerException e){[Link](e);}
Test it Now
Case 3
try{
int data=25/0;
[Link](data);
catch(ArithmeticException e){[Link](e);}
Test it Now
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.
throw exception;
1 In this example, we have created the validate method that takes integer value as a
2 parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise
3 print a message welcome to vote.
4
5 public class TestThrow1{
6
7 static void validate(int age){
8
9 if(age<18)
10
11 throw new ArithmeticException("not valid");
12
13 else
14
15 [Link]("welcome to vote");
16
17 }
18
19 public static void main(String args[]){
20
21 validate(13);
22
23 [Link]("rest of the code...");
24
25 }
26
27 }
28
29 Test it Now
30
31 Output:
32
33 Exception in thread main [Link]:not valid
34
35 Java Exception propagation
36
37 An exception is first thrown from the top of the stack and if it is not caught, it drops
38 down the call stack to the previous method,If not caught there, the exception again drops
39 down to the previous method, and so on until they are caught or until they reach the very
40 bottom of the call [Link] is called exception propagation.
41
42 Rule: By default Unchecked Exceptions are forwarded in calling chain (propagated).
43
44 Program of Exception Propagation
45
46 class TestExceptionPropagation1{
47
48 void m(){
49
50 int data=50/0;
51
52 }
53
54 void n(){
55
56 m();
57
58 }
59
60 void p(){
try{
n();
obj.p();
[Link]("normal flow...");
Test it Now
Output:exception handled
normal flow...
exception propagation
In the above example exception occurs in m() method where it is not handled,so it is propagated
to previous n() method where it is not handled, again it is propagated to p() method where
exception is handled.
Exception can be handled in any method in call stack either in main() method,p() method,n()
method or m() method.
Rule: By default, Checked Exceptions are not forwarded in calling chain (propagated).
class TestExceptionPropagation2{
void m(){
void n(){
m();
void p(){
try{
n();
obj.p();
[Link]("normal flow");
Test it Now
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
//method code
error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
import [Link];
class Testthrows1{
m();
void p(){
try{
n();
obj.p();
[Link]("normal flow...");
Test it Now
Output:
exception handled
normal flow...
Rule: If you are calling a method that declares an exception, you must either caught or declare
the exception.
Case1:You caught the exception i.e. handle the exception using try/catch.
Case2:You declare the exception i.e. specifying throws with the method.
In case you handle the exception, the code will be executed fine whether exception occurs during
the program or not.
import [Link].*;
class M{
try{
M m=new M();
[Link]();
[Link]("normal flow...");
Test it Now
Output:exception handled
normal flow...
A) In case you declare the exception, if exception does not occur, the code will be executed fine.
B) In case you declare the exception if exception occures, an exception will be thrown at runtime
because throws does not handle the exception.
import [Link].*;
class M{
class Testthrows3{
M m=new M();
[Link]();
[Link]("normal flow...");
Test it Now
normal flow...
import [Link].*;
class M{
class Testthrows4{
M m=new M();
[Link]();
[Link]("normal flow...");
Test it Now
Output:Runtime Exception
4) Throw is used within the method. Throws is used with the method
signature.
5) You cannot throw multiple You can declare multiple exceptions e.g.
exceptions. public void method()throws
IOException,SQLException.
void m(){
//method code