JavaProgramming Unit-II
JavaProgramming 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
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
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
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;
Programmer();
System.out.println("Bonus of Programmer
is:"+p.bonus);
Output:
Programmer salary
is:40000.0 Bonus of
programmer is:10000
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...");}
void bark(){System.out.println("barking...");}
class TestInheritance{
Dog(); d.bark();
d.eat();
}}
Output:
barking...
eating...
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
BabyDog(); d.weep();
d.bark();
d.eat();
}} Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
void meow(){System.out.println("meowing..."); }
}
class TestInheritance3{
{
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.
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";
color="black";
void printColor(){
}}
class TestSuper1{
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...");}
void eat(){System.out.println("eating
bread...");} void
bark(){System.out.println("barking...");} void
work(){
super.eat();
bark();
}
class TestSuper2{
d.work();
}}
Output:
eating...
barking...
The super keyword can also be used to invoke the parent class constructor. Let's see a simple
Animal(){System.out.println("animal is created");}
}
class Dog extends
Animal{ Dog(){
super();
System.out.println("dog is created");
}}
class TestSuper3{
}}
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
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
void run()
{
System.out.println("Vehicle is running");
}}
obj.run(); }
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
Note 1 : Dynamic Method dispatch also comes under RuntimePolymorphism . refer lab program for this.
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.
A method which is declared as abstract and does not have implementation is known as 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
1. variable
2. method
3. class
final variable
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400; //error
}
Output:Compile Time Error
}
public static void main(String args[])
Honda(); honda.run();
}
}
void run()
Honda1( ); honda.run( );
}}
Interfaces
An interface in java is a blueprint of a class. It has static constants and abstract methods.
Or
There are mainly three reasons to use interface. They are given below.
Declaration of an interface
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
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 {
System.out.println("eats nonveg");
}
public void travel() {
return 4;
m.travel();
int x= m.noOfLegs();
System.out.println(x);
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
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
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
//save as Simple.java
package mypack; public
class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
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. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
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.
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.
//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
//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
Output:Hello subpackage
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("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.
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.
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.
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.
1. Checked Exception
2. Unchecked Exception
3. Error
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.
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.
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.
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.
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);
}
}
}
catch(NullPointerException e)
{
System.out.println("Caught inside
fun()."); throw e; // rethrowing
the exception
}
}
}
catch(NullPointerException e)
{
System.out.println("Caught in main.");
}
}
}
Output:
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.
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");
{}