0% found this document useful (0 votes)
2 views

JavaProgramming Unit-II

This document covers key concepts in Java programming, including inheritance, polymorphism, abstract classes, interfaces, packages, and exception handling. It explains inheritance as a mechanism for code reusability and method overriding, while polymorphism is introduced through method overriding and overloading. Additionally, it discusses the use of abstract classes and interfaces for achieving abstraction and multiple inheritance, along with the structure and usage of Java packages.

Uploaded by

anudeepmolugu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JavaProgramming Unit-II

This document covers key concepts in Java programming, including inheritance, polymorphism, abstract classes, interfaces, packages, and exception handling. It explains inheritance as a mechanism for code reusability and method overriding, while polymorphism is introduced through method overriding and overloading. Additionally, it discusses the use of abstract classes and interfaces for achieving abstraction and multiple inheritance, along with the structure and usage of Java packages.

Uploaded by

anudeepmolugu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

UNIT –II

Topics:
 Inheritance
 Polymorphism
 Interfaces
 Abstract Classes
 Packages
 Exception Handling
Inheritance
Inheritance is a mechanism in which one object acquires all the properties and behaviors of a parent object.

Or

Creating a new class from the existing class

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java

 For Method Overriding (so runtime polymorphism can be achieved). 


 For Code Reusability. 

Terms used in Inheritance

 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 the previous class. 
 “ extends “ keyword is used to have inheritance in java
The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

Programmer is the subclass and Employee is the superclass. The relationship between the two classes is
Programmer IS-A Employee. It 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();

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

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java:

 Single – one base class and one derived class in only one level
 multilevel – one base class and one derived class in different levels
 hierarchical. – one base class and multiple derived classes
Single Inheritance Example

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...

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...
Hierarchical Inheritance 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...

‘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.

 super is used to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of parent class. It is used if parent class and
child class have same fields.

class Animal{

String color="white";

class Dog extends Animal{


String

color="black";

void printColor(){

System.out.println(color);//prints color of Dog class

System.out.println(super.color); //prints color of Animal class

}}
class TestSuper1{

public static void main(String

args[]){ Dog d=new Dog();

rintColor();

}}

Output: black

White
 super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used if subclass contains
the same method as parent class. In other words, it is used if method is overridden.

class Animal{

void eat(){System.out.println("eating...");}

class Dog extends Animal{

void eat(){System.out.println("eating

bread...");} void

bark(){System.out.println("barking...");} void

work(){

super.eat();

bark();

}
class TestSuper2{

public static void main(String

args[]){ Dog d=new Dog();

d.work();

}}
Output:

eating...
barking...

 super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor. Let's see a simple

example: class Animal{

Animal(){System.out.println("animal is created");}

}
class Dog extends

Animal{ Dog(){

super();

System.out.println("dog is created");

}}

class TestSuper3{

public static void main(String

args[]){ Dog d=new Dog();

}}
Output:
animal is created

dog is created

Polymorphism
 If a super class and sub class are having same method with same name , parameters and return
type (full method signature) it is called Runtime polymorphism

 Runtime polymorphism is implemented using Method Overriding , i.e here which function has to
be over loaded is known only at run time which is based on super class object or sub class object.

Method Overriding
If subclass (child class) has the same method (full method signature) as declared in the parent class, it is
known as method overriding in java.
Usage of Java Method Overriding

 Method overriding is used to provide specific implementation of a method that is already provided by
its super class.
 Method overriding is used for runtime polymorphism
Rules for Java Method Overriding

1. method must have same name as in the parent class


2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

Example of 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 parameter and return type of the method is same in super class and sub

class class Vehicle{

void run()

{
System.out.println("Vehicle is running");

}}

class Bike2 extends Vehicle{

void run(){System.out.println("Bike is running

safely");} public static void main(String args[]){

Bike2 obj = new Bike2();

obj.run(); }

Output:Bike is running safely


Real example of Java Method Overriding

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.
Difference between method overloading and method overriding in java

No. Method Overloading Method Overriding


Method overriding is used to provide the
Method overloading is used to increase the readability of the
1) specific implementation of the method that
program.
is already provided by its super class.

Method overriding occurs in two classes


2) Method overloading is performed within class.
that have IS-A (inheritance) relationship.
In case of method overriding, parameter
3) In case of method overloading, parameter must be different.
must be same.
Method overloading is the example of compile time Method overriding is the example of run
4)
polymorphism. time polymorphism.
In java, method overloading can't be performed by changing
return type of the method only. Return type can be same or Return type must be same or covariant in
5)
different in method overloading. But you must have to change method overriding.
the parameter.

Note 1 : Dynamic Method dispatch also comes under RuntimePolymorphism . refer lab program for this.

Note 2 : Refer Method Overloading for compile time polymorphism.

Abstract classes
A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

 An abstract class must be declared with an abstract keyword.


 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of the method.

Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as an abstract method.

Example of abstract method

 abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.

abstract class

Bike{ abstract

void run();

}
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

‘final’ Keyword
The final keyword in java is used to restrict the

user. The java final keyword can be used in many


context. Final can be:

1. variable
2. method
3. class

 final variable

 If you declare any variable as final, It will be constant


 you cannot change the value of final variable

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400; //error
}
Output:Compile Time Error

 final method or final with inheritance

If you declare any method as final, you cannot override it.

Example of final method


class Bike{

final void run(){System.out.println("running");} }

class Honda extends

Bike{ void run() //error

System.out.println("running safely with 100kmph");

}
public static void main(String args[])

Honda honda= new

Honda(); honda.run();

}
}

Output:Compile Time Error


 Java final class or final with inheritance

If you make any class as final, you cannot extend it.

Example of final class

final class Bike{ }

class Honda1 extends Bike //error

void run()

System.out.println("running safely with 100kmph");

public static void main(String

args[]){ Honda1 honda= new

Honda1( ); honda.run( );

}}

Output:Compile Time Error

Interfaces
An interface in java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction.

Or

Interface is the collection of abstract methods and final variables

 Interface fields or variables are public, static and final by default,


 The methods are public and abstract.

There are mainly three reasons to use interface. They are given below.

o It is used to achieve 100% abstraction.


o By interface, we can support the functionality of multiple inheritance.

Declaration of an interface

 An interface is declared by using the “interface” keyword.


 A class implements the interface using “implements” keyword
 A class that implements an interface must implement all the methods declared in the interface.

Syntax:

interface <interface_name>

{
// declare constant fields
// declare methods that abstract
// by default.
}

Example : interface Animal {

final String type=”wild animals”;

public void eat();

public void travel();

Implementing Interfaces
 A class uses the implements keyword to implement an interface.

 The implements keyword appears in the class declaration following the extends portion of the
declaration.

 Whenever a class is implementing interface it has to implement all the methods of interface and must
be declared as public .

Example
public class TigerInterface implements Animal {

public void eat() {

System.out.println("eats nonveg");

}
public void travel() {

System.out.println("runs very fast");

public int noOfLegs() {

return 4;

public static void main(String args[]) {

MammalInt m = new MammalInt();


m.eat();

m.travel();

int x= m.noOfLegs();

System.out.println(x);

} Output eats nonveg

runs very fast

Extending Multiple Interfaces


 An interface can extend more than one interface.

 “extends “ keyword is used to extend interfaces

 As java does not support multiple inheritance. Using interfaces multiple inheritance can be achieved (
by extending multiple interfaces)

 A class can implement multiple interfaces and also interface can extend more than one interface which
achieves multiple inheritance in java

 To extend multiple interfaces extends keyword is used once, and the parent interfaces are declared in a
comma-separated list.
For example, if the Hockey interface extended both Sports and Event, it would be declared as –
public interface Hockey extends Sports, Event

Example which supports multiple inheritance through interfaces


interface Inf1{
public void
A();
}
interface Inf2 extends
Inf1 { public void B();
}
interface Inf3 {
public void
C();
}

public class InterfaceDemo implements Inf2,Inf3{


public void A(){
System.out.println("Hello");
}
public void B(){
System.out.println("GUYs");
}
public void C(){
System.out.println("Welcome to VJIT");
}
public static void main(String args[]){
InterfaceDemo obj = new InterfaceDemo
(); obj.A();
obj.B();
obj.C();
} }
Output:
Hello GUYS
Welcome to VJIT
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. Here, we will have

the detailed learning of creating and using user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Simple example of java package

The package keyword is used to create a package in java.

//save as Simple.java
package mypack; public
class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How to compile java package

syntax given below:

javac -d directory javafilename


For example
javac -d . Simple.java

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).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents
the current folder.

Access a package from another package


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 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.

Example of package that import the packagename.*

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){ A obj =
new A();
obj.msg();
}
}
Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname

//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){ A obj =
new A();
obj.msg();
}
}
Output:Hello

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 or
interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date
class.

Example of package by import fully qualified name

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack; class
B{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello

If you import a package, all the classes and interface of that package will be imported excluding the classes
Example of Subpackage

package com.javaoe.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java

To Run: java com.javaoe.core.Simple

Output:Hello subpackage

To send the class file to another directory or drive


If want to put the class file of A.java source file in classes folder of c: drive. For example:

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

To Compile:

e:\sources> javac -d c:\classes Simple.java

To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the class file resides.

e:\sources> set classpath=c:\classes;.;

e:\sources> java mypack.Simple

Another way to run this program by -classpath switch of java:


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 where to look
for class file. For example:
e:\sources> java -classpath c:\classes mypack.Simple

Output:Welcome to package
Access Modifiers in Java
As the name suggests access modifiers in Java helps to restrict the scope of a class, constructor ,
variable , method or data member. There are four types of access modifiers available in java:
1. Default – No keyword required
2. Private
3. Protected
4. Public

Note : Default: When no access modifier is specified for a class , method or data member – It is said to
be having the default access modifier by default.

Exception Handling
The Exception Handling is a powerful mechanism to handle the runtime errors so that normal flow of the program execution can be
maintained even though an exception occurs during run time.

 Exception is an abnormal condition.

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 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. An exception normally disrupts the
normal flow of the application that is why we use exception handling.

Example:

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;
Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest of the
code will not be executed i.e. statement 6 to 10 will not be executed. If we perform exception handling, the rest
of the statement will be executed. That is why we use exception handling in Java.

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses:
Exception and Error.

A hierarchy of Java Exception classes are given below:


Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked exception. According
to Oracle, there are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked Exceptions


1) Checked Exception
The classes which directly inherit 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 which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords


There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

try The "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 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 important code of the program. It is executed
whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It
specifies that there may occur an exception in the method. It is always used with method
signature.

Java Exception Handling Example


public class JavaExceptionExample{ public static
void main(String args[]){ try{

//code that may raise exception


int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

Output:
Exception in thread main
java.lang.ArithmeticException:/ by zero rest of the
code...
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.

User defined Exception subclass


You can also create your own exception sub class simply by extending java Exception class.
class MyException extends Exception
{
private int ex;
MyException(int a)
{
ex=a;
}
public String toString()
{
return "MyException[" + ex +"] is less than zero";
}
}

class Test
{
static void sum(int a,int b) throws MyException
{
if(a<0)
{
throw new MyException(a); //calling constructor of user-defined exception class
}
else
{
System.out.println(a+b);
}
}

public static void main(String[] args)


{
try
{
sum(-10, 10);
}
catch(MyException me)
{
System.out.println(me); }}
//it calls the toString() method of user-defined Exception

MyException[-10] is less than zero


throw
The throw keyword in Java is used to explicitly throw an exception from a method or any block of
code. We can throw either checked or unchecked exception. The throw keyword is mainly used to
throw custom exceptions.
Syntax: throw Instance;

Example: throw new ArithmeticException("/ by zero");

// Java program that demonstrates the use


of throw class ThrowExcep
{
static void fun()
{
tr
y
{ throw new NullPointerException("demo");

}
catch(NullPointerException e)
{
System.out.println("Caught inside
fun()."); throw e; // rethrowing
the exception
}
}

public static void main(String args[])


{
try
{
fun();

}
catch(NullPointerException e)
{
System.out.println("Caught in main.");
}
}
}

Output:

Caught inside fun().


Caught in main.
throws
throws is a keyword in Java which is used in the signature of 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:
type method_name(parameters) throws exception_list
exception_list is a comma separated list of all the exceptions which a method might throw.
Example :
class ThrowsExecp
{
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
fun();
}
catch(IllegalAccessException e)
{
System.out.println("caught in main.");
}
}} Output: Inside fun().
caught in main.

No. throw throws

1) Java throw keyword is used to explicitly throw Java throws keyword is used to declare an
an exception. exception.

2) Checked exception cannot be propagated using Checked exception can be propagated with
throw only. throws.

3) Throw is used within the method. Throws is used with the method signature.

4) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.

5) Syntax: Syntax:
throw Instance method_name(parameters) throws exception_list

Example: Example :
throw new ArithmeticException("/ by
void getData() throws IOException
zero");
{}

You might also like