0% found this document useful (0 votes)
9 views30 pages

Module 3 & 4 Mix (Shivani Ma - Am)

Uploaded by

moh24amme
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)
9 views30 pages

Module 3 & 4 Mix (Shivani Ma - Am)

Uploaded by

moh24amme
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/ 30

Module 3 -Java

Inheritance:

Inheritance in java is a mechanism in which one object acquires all the properties and
behaviours 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.
Inheritance represents the IS-A relationship, also known as parent-child relationship. The
class which inherits the properties of other is known as subclass (derived class, child class) and
the class whose properties are inherited is known as superclass (base class, parent class).
extends is the keyword used to inherit the properties of a class.

Use of inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

1. class Employee
2. {
3. float salary=40000;
4. }
5.
6. class Programmer extends Employee
7. {
8. int bonus=10000;
9. public static void main(String args[])
{
Programmer p=new Programmer();

Mrs Srivani P BMSIT&M Page 1


Module 3 -Java

System.out.println("Programmer salary is:"+p.salary);


System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000

Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance

Single Level Inheritance :


One class extends one class only

1. class Animal
2. {
3. void eat()
4. {
5. System.out.println("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void bark()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}

Mrs Srivani P BMSIT&M Page 2


Module 3 -Java

barking...
eating...

Multilevel Inheritance:
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from
a derived class, thereby making this derived class the base class for the new class.

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();
}
}
weeping...
barking...
eating..

Hierarchical Inheritance :

In simple terms you can say that Hybrid inheritance is a combination


of Single and Multiple inheritance. In Hierarchical inheritance one parent class will be
inherited by many sub classes.
class Animal{
void eat(){System.out.println("eating...");}

Mrs Srivani P BMSIT&M Page 3


Module 3 -Java

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();//Compile Time.Error
}}
meowing...
eating...

Polymorphism:
Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in java:
• compile time polymorphism and
• runtime polymorphism.
Compile Time polymorphism can be achieved using overloading methods
Run Time Polymorphism can be achieved using overriding methods

Runtime Polymorphism
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.

Child class has the same method as of base class. In such cases child class overrides the parent
class method without even touching the source code of the base class.

Advantage 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 Method Overriding


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

Mrs Srivani P BMSIT&M Page 4


Module 3 -Java

class Bank{
float getRateOfInterest(){
return 0;
}
}
class SBI extends Bank{
float getRateOfInterest(){
return 8.4f;
}
}
class ICICI extends Bank{
float getRateOfInterest(){
return 7.3f;
}
}
class AXIS extends Bank{
float getRateOfInterest(){
return 9.7f;
}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}
SBI Rate of Interest: 8.4
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

Mrs Srivani P BMSIT&M Page 5


Module 3 -Java

Difference between Overloading and Overriding


Overloading Overriding
Whenever same method or Constructor is Whenever same method name is existing
existing multiple times within a class either multiple time in both base and derived
1 with different number of parameter or with class with same number of parameter or
different type of parameter or with different same type of parameter or same order of
order of parameter is known as Overloading. parameters is known as Overriding.
Arguments of method must be different at Argument of method must be same
2
least arguments. including order.
3 Method signature must be different. Method signature must be same.
Private, static and final methods can be Private, static and final methods can not be
4
overloaded. override.
Access modifiers point of view not reduced
5 Access modifiers point of view no restriction.
scope of Access modifiers but increased.
Also known as compile time polymorphism or Also known as run time polymorphism or
6
static polymorphism or early binding. dynamic polymorphism or late binding.
Overloading can be exhibited both are method Overriding can be exhibited only at method
7
and constructor level. label.
The scope of Overriding is base class and
8 The scope of overloading is within the class.
derived class.
Overloading can be done at both static and Overriding can be done only at non-static
9
non-static methods. method.
For overloading methods return type may or For overriding method return type should
10
may not be same. be same.

NOTE : Static methods cannot be overridden because, a static method is bounded with class
where as instance method is bounded with object.

Mrs Srivani P BMSIT&M Page 6


Module 3 -Java

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.

1) super is used to refer immediate parent class instance variable.


This scenario occurs when a derived class and base class has same data members. Hence we
use super keyword to refer a member of immediate parent class.

class Vehicle
{
int maxSpeed = 120;
}

class Car extends Vehicle


{
int maxSpeed = 180;

void display()
{
System.out.println("Derived class Speed: " + maxSpeed);
System.out.println("Base Speed: " + super.maxSpeed);
}
}

/* Driver program to test */


class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Derived class Speed: 180
Base class Speed: 120

2) super can be used to invoke parent class method

The super keyword can also be used to invoke or call parent class method. It should be used
in case of method overriding. In other word super keyword use when base class method name
and derived class method name have same name.

Mrs Srivani P BMSIT&M Page 7


Module 3 -Java

class Student
{
void message()
{
System.out.println("Good Morning Sir");
}
}

class Faculty extends Student


{
void message()
{
System.out.println("Good Morning Students");
}

void display()
{
message(); //will invoke or call current class message() method
super.message(); //will invoke or call parent class message() method
}

public static void main(String args[])


{
Student s=new Student();
s.display();
}
}
Good Morning Students
Good Morning Sir

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke or call the parent class constructor.
Constructor are calling from bottom to top and executing from top to bottom.
To establish the connection between base class constructor and derived class constructors
JVM provides two implicit methods they are: If super is not used explicitly compiler will
automatically add super as the first statement.

• Super()
• Super(...)

Super():
Super() It is used for calling super class default constructor from the context of derived
class constructors.
class Employee
{
Employee()
{
System.out.println("Employee class Constructor");
}

Mrs Srivani P BMSIT&M Page 8


Module 3 -Java

}
class HR extends Employee
{
HR()
{
super(); //will invoke or call parent class constructor
System.out.println("HR class Constructor");
}
}
class Supercons
{
public static void main(String[] args)
{
HR obj=new HR();
}
}
Employee class Constructor
HR class Constructor

Super(...)
Super(...) It is used for calling super class parameterize constructor from the context of
derived class constructor.

class Person
{
int id;
String name;

Person(int id,String name)


{
this.id=id;
this.name=name;
}
}
class Emp extends Person
{
float salary;
Emp(int id,String name,float salary)
{
super(id,name); //reusing parent constructor
this.salary=salary;
}
void display()
{
System.out.println(id+" "+name+" "+salary);}
}

class TestSuper5
{

Mrs Srivani P BMSIT&M Page 9


Module 3 -Java

public static void main(String[] args)


{
Emp e1=new Emp(1,"abc",5000f);
e1.display();
}
}
1 abc 5000

Important rules
Rule for default constructor
Whenever the derived class constructor want to call default constructor of base class, in the
context of derived class constructors we write super(). It is optional to write because every
base class constructor contains single form of default constructor
Rule for Parameterized constructor
Whenever the derived class constructor wants to call parameterized constructor of base class
in the context of derived class constructor we must write super(...). which is mandatory to
write because a base class may contain multiple forms of parameterized constructors.

Abstract Classes
An abstract class is a class that is declared abstract—It can have abstract and non-abstract
methods (method with body).Abstract classes cannot be instantiated, but they can be
subclassed.
That is we cannot create an object for abstract classes
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.
• To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
• If you inherit an abstract class, you have to provide implementations to all the abstract
methods in it.

Abstract method

Method that is declared without any body within an abstract class is called abstract method.
The method body will be defined by its subclass. Abstract method can never be final and static.

Mrs Srivani P BMSIT&M Page 10


Module 3 -Java

Any class that extends an abstract class must implement all the abstract methods declared by
the super class.

Syntax :

abstract return_type function_name ();

abstract class Shape


{
abstract void draw();
}

class Rectangle extends Shape{


void draw(){
System.out.println("drawing rectangle");}
}

class Circle extends Shape{


void draw(){
System.out.println("drawing circle");}
}

class TestAbstraction
{
public static void main(String args[])
{
Rectangle r = new Rectangle();
r.draw();
Shape s=new Circle();
s.draw();
}
}
drawing rectangle
drawing circle

abstract class Bank{


abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}

class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();

Mrs Srivani P BMSIT&M Page 11


Module 3 -Java

System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");


b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}
Rate of Interest is: 7 %
Rate of Interest is: 8 %

Abstract classes with constructors


abstract class Bike
{
Bike(){
System.out.println("bike is created");
}
abstract void run();

void changeGear(){
System.out.println("gear changed");}
}

class Honda extends Bike{


void run(){
System.out.println("running safely..");
}
}
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
bike is created
running safely..
gear changed

When to use Abstract Methods & Abstract Class?


Abstract methods are usually declared where two or more subclasses are expected to
do a similar thing in different ways through different implementations. These subclasses extend
the same Abstract class and provide different implementations for the abstract methods.
Abstract classes are used to define generic types of behaviours at the top of an object-oriented
programming class hierarchy, and use its subclasses to provide implementation details of the
abstract class.

Packages:
Packages in Java is a mechanism to encapsulate a group of classes, interfaces and sub
packages.To create a package is quite easy: simply include a package command as the first

Mrs Srivani P BMSIT&M Page 12


Module 3 -Java

statement in a Java source file. Any classes declared within that file will belong to the specified
package. The package statement defines a name space in which classes are stored. If you omit
the package statement, the class names are put into the default package, which has no name.
This is the general form of the package statement:
package pkg;

Java uses file system directories to store packages. For example, the .class files for any classes
you declare to be part of MyPackage must be stored in a directory called MyPackage.

You can create a hierarchy of packages.

package pkg1[.pkg2[.pkg3]];

Ex: package java.awt.image;

Advantages of using a package


• Reusability: Reusability of code is one of the most important requirements in the
software industry. Reusability saves time, effort and also ensures consistency. A class
once developed can be reused by any number of programs wishing to incorporate the
class in that particular program.
• Easy to locate the files.
• In real life situation there may arise scenarios where we need to define files of the same
name. This may lead to “name-space collisions”. Packages are a way of avoiding “name-
space collisions”.

Package are categorized into two forms


• Built-in Package:-Existing Java package for example java.lang, java.util etc.
• User-defined-package:- Java package created by user to categorized classes and interface

How to compile & Run java package?


If you are not using any IDE, you need to follow this:
Compile :- javac -d . Simple.java
Run :- java mypack.Simple

Mrs Srivani P BMSIT&M Page 13


Module 3 -Java

How to access 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 sub packages. 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();
}
}

1) Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.

1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
}

Mrs Srivani P BMSIT&M Page 14


Module 3 -Java

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

1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }

Access Specifiers
• private: accessible only in the class
• default : so-called “package” access — accessible only in the same package
• protected: accessible (inherited) by subclasses, and accessible by code in same package
• public: accessible anywhere the class is accessible, and inherited by subclasses

Notice that private protected is not syntactically legal.

Exception Handling in Java

An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
• A user has entered an invalid data.

Mrs Srivani P BMSIT&M Page 15


Module 3 -Java

• A file that needs to be opened cannot be found.


• A network connection has been lost in the middle of communications or the JVM has
run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
Difference between error and exception
Errors indicate serious problems and abnormal conditions that most applications should not
try to handle. Error defines problems that are not expected to be caught under normal
circumstances by our program. For example memory error, hardware error, JVM error etc.
Exceptions are conditions within the code. A developer can handle such conditions and take
necessary corrective actions.

Few examples –
• DivideByZero exception
• NullPointerException
• ArithmeticException
• ArrayIndexOutOfBoundsException

Advantages of Exception Handling


• Exception handling allows us to control the normal flow of the program by using
exception handling in program.
• It throws an exception whenever a calling method encounters an error providing that
the calling method takes care of that error.
• It also gives us the scope of organizing and differentiating between different error types
using a separate block of codes. This is done with the help of try-catch blocks.

Exception hierarchy

Mrs Srivani P BMSIT&M Page 16


Module 3 -Java

In Java, there are two types of exceptions:

1) Checked: are the exceptions that are checked at compile time. If some code within a method
throws a checked exception, then the method must either handle the exception or it must specify
the exception using throws keyword.

Example, consider the following Java program that opens file at location “C:\test\a.txt” and
prints the first three lines of it. The program doesn’t compile, because the function main() uses
FileReader() and FileReader() throws a checked exception FileNotFoundException. It also
uses readLine() and close() methods, and these methods also throw checked exception
IOException

2) Unchecked are the exceptions that are not checked at compiled time. In C++, all exceptions
are unchecked, so it is not forced by the compiler to either handle or specify the exception. It
is up to the programmers to be civilized, and specify or catch the exceptions.

In Java exceptions under Error and RuntimeException classes are unchecked exceptions,
everything else under throwable is checked.

Java Exception Handling Keywords


Mrs Srivani P BMSIT&M Page 17
Module 3 -Java

Java provides specific keywords for exception handling purposes,


1. try
2. catch
3. finally
4. throw
5. throws

try-catch –

try is the start of the block and catch is at the end of try block to handle the exceptions.
We can have multiple catch blocks with a try and try-catch block can be nested also. catch
block requires a parameter that should be of type Exception.
A catch block must be associated with a try block. The corresponding catch block
executes if an exception of a particular type occurs within the try block.
For example if an arithmetic exception occurs in try block then the statements enclosed
in catch block for arithmetic exception executes.

Syntax of try catch in java


try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}

import java.io.*;

public class ExcepTest


{
public static void main(String args[])
{
try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}

Mrs Srivani P BMSIT&M Page 18


Module 3 -Java

class Excp
{
public static void main(String args[])
{
int a,b,c;
try
{
a=0;
b=10;
c=b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}

Multiple Catch Blocks


A try block can be followed by multiple catch blocks.
If the try block throws an exception, the appropriate catch block (if one exists) will catch it
–catch(ArithmeticException e) is a catch block that can catch ArithmeticException
–catch(NullPointerException e) is a catch block that can catch NullPointerException

All the statements in the catch block will be executed and then the program continues.
If the exception type of exception, matches with the first catch block it gets caught, if not the
exception is passed down to the next catch block.

class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}

Mrs Srivani P BMSIT&M Page 19


Module 3 -Java

Warning: ArithmeticException
Out of try-catch block...

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.
Finally block is optional and can be used only with try-catch block. Since exception halts
the process of execution, we might have some resources open that will not get closed, so we
can use finally block. finally block gets executed always, whether exception occurred or not

1. class TestFinallyBlock1{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e)
8. {
9. 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

Java throws keyword

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.

throws – When we are throwing any exception in a method and not handling it, then we need
to use throws keyword in method signature to let caller program know the exceptions that
might be thrown by the method. The caller method might handle these exceptions or propagate

Mrs Srivani P BMSIT&M Page 20


Module 3 -Java

it to its caller method using throws keyword. We can provide multiple exceptions in the throws
clause and it can be used with main() method also.

Syntax of java throws


return_type method_name() throws exception_class_name
{
//method code
}

throw –
We know that if any exception occurs, an exception object is getting created and then
Java runtime starts processing to handle them. Sometime we might want to generate exception
explicitly in our code, for example in a user authentication program we should throw exception
to client if the password is null. throw keyword is used to throw exception to the runtime to
handle it.

Throw instance();

where,
instance is of object type of an exception.

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

import java.io.*;
class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException ("demo Exception ");
}

public static void main(String args[])


{

try
{
check();
}
catch(ArithmeticException e)
{
System.out.println("caught in main\n" + e);
}
}
}
Output:Inside check function
caught in main

Mrs Srivani P BMSIT&M Page 21


Module 3 -Java

java.lang.ArithmeticException: demo Exception

What is the difference between throw and throws?

throw throws

It is used to create a new Exception object It is used in method definition, to declare


and throw it that a risky method is being called.

Using throw keyword you can declare only Using throws keyword you can declare
one Exception at a time multiple exception at a time.

Example: Example:

throw new IOException("can not open throws IOException,


connection"); ArrayIndexBoundException;

USER_DEFINED EXCEPTION HANDLING- throw & throws

import java.io.*;

class InsufficientFundsException extends Exception


{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;

}
public double getAmount()
{
return amount;
}
}
public class Main
{
private double balance;
private int number;
public Main(int balance)
{
this.balance = balance;
}

Mrs Srivani P BMSIT&M Page 22


Module 3 -Java

public void withdraw(double amount) throws InsufficientFundsException


{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}

public static void main(String[] args) {


System.out.println("Hello World");
Main c= new Main(1000);
try {
c.withdraw(2000);
} catch(InsufficientFundsException e) {
System.out.println("Sorry, but you are short $"
+ e.getAmount());
e.printStackTrace();
} finally {
}

}
}
Output:
Hello World
Sorry, but you are short $1000.0
InsufficientFundsException
at Main.withdraw(Main.java:42)

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. There can be only abstract methods
in the java interface not method body. It is used to achieve abstraction and multiple inheritance
in Java.

Java Interface also represents IS-A relationship.It cannot be instantiated just like abstract
class.

There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

Mrs Srivani P BMSIT&M Page 23


Module 3 -Java

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

Syntax:

access_modifier interface nameofinterface


{
Function prototype1;
Function Prototype 2;
Type static final variable= value;
}

Rules for using Interface


• Methods inside Interface must not be static, final.
• All variables declared inside interface are implicitly public static final
variables(constants).
• All methods declared inside Java Interfaces are implicitly public and abstract, even if you
don't use public or abstract keyword.
• Interface can extend one or more other interface.
• Interface cannot implement a class.
• Interface can be nested inside another interface.
• Interface cannot be declared as private, protected.
• Variables declared in interface are public, static and final by default.

1. interface Bank
2. {
3. float rateOfInterest();
4. }
5.
6. class SBI implements Bank
7. {
8. public float rateOfInterest()
9. {
10. return 9.15f;
}
}
class PNB implements Bank
{
public float rateOfInterest()
{
return 9.7f;
}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}
}

Mrs Srivani P BMSIT&M Page 24


Module 3 -Java

abstract Classes Interfaces

1 abstract class can extend only one class or one interface can extend any number of
abstract class at a time interfaces at a time

2 abstract class can extend from a class or from an interface can extend only from an
abstract class interface

3 abstract class can have both abstract and interface can have only abstract methods
concrete methods
4 A class can extend only one abstract class A class can implement any number of
interfaces

5 In abstract class keyword ‘abstract’ is mandatory In an interface keyword ‘abstract’ is


to declare a method as an abstract optional to declare a method as an abstract
6 abstract class can have protected , public and Interface can have only public abstract
public abstract methods methods i.e. by default
7 abstract class can have static, final or static interface can have only static final
final variable with any access specifier (constant) variable i.e. by default

abstract class Shape {

abstract double area();

}
public interface Drawable {
public abstract void draw();

public class Circle extends Shape implements Drawable {

double radius;

Circle(double aRadius){

radius= aRadius;
}

double area(){

Mrs Srivani P BMSIT&M Page 25


Module 3 -Java

return Math.PI*radius*radius;
}

public void draw(){


System.out.println("This is a circle");
}

}
Class test
{
Public static void main(String args[])
{
Shape obj= new Rectangle();
Shape obj1= new Circle();

obj.draw();
obj1.draw();
}
}

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends another interface, but
a class implements an interface.

Example: interface Bank{


float rateOfInterest();
}
class SBI implements Bank
{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}

Mrs Srivani P BMSIT&M Page 26


Module 3 -Java

class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}
}
Output: ROI: 9.15

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritance.

1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class Test implements Printable,Showable{
8. public void print(){
9. System.out.println("Hello");}

public void show(){


System.out.println("Welcome");}

public static void main(String args[]){


Test obj = new Test ();
obj.print();
obj.show();
}

Mrs Srivani P BMSIT&M Page 27


Module 3 -Java

Output:Hello
Welcome

Interface and Inheritance


An interface cannot implement another interface. It has to extend the other interface. See the
below example where we have two interfaces Inf1 and Inf2. Inf2 extends Inf1 so If class
implements the Inf2 it has to provide mplementation of all the methods of interfaces Inf2 as
well as Inf1.

interface Inf1{
public void method1();
}
interface Inf2 extends Inf1 {
public void method2();
}
public class Demo implements Inf2{
/* Even though this class is only implementing the
* interface Inf2, it has to implement all the methods
* of Inf1 as well because the interface Inf2 extends Inf1
*/
public void method1(){
System.out.println("method1");
}
public void method2(){
System.out.println("method2");
}
public static void main(String args[]){
Inf2 obj = new Demo();
obj.method2();
}
}

Final Class, Final methods & Final variables:

Final methods:
While method overriding is one of Java’s most powerful features, there will be times when you
will want to prevent it from occurring. To disallow a method from being overridden, specify
final as a modifier at the start of its declaration. Methods declared as final cannot be
overridden.

The following fragment illustrates final:

Mrs Srivani P BMSIT&M Page 28


Module 3 -Java

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

class Honda extends Bike


{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Complie Time Error as Final methods cannot be overridden

Final Class:
Sometimes you will want to prevent a class from being inherited. To do this, precede the class
declaration with final. Declaring a class as final implicitly declares all of its methods as final,
too. As you might expect, it is illegal to declare a class as both abstract and final since an
abstract class is incomplete by itself and relies upon its subclasses to provide complete
implementations.
Here is an example of a final class:
1. final class Bike{}
2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda();
8. honda.run();
9. }
}
Output:Compile Time Error

Final variable
If you make any variable as final, you cannot change the value of final variable
(It will be constant).
1. class Bike
2. {
3. final int speedlimit=90; //final variable

Mrs Srivani P BMSIT&M Page 29


Module 3 -Java

4. void run()
5. {
6. speedlimit=400;
7. }
8. public static void main(String args[]){
9. Bike9 obj=new Bike9();
obj.run(); //Compile Time Error
}
}
Compile Time Error

Mrs Srivani P BMSIT&M Page 30

You might also like