0% found this document useful (0 votes)
43 views39 pages

Unit-Ii Java R20

Uploaded by

panduy.ent
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)
43 views39 pages

Unit-Ii Java R20

Uploaded by

panduy.ent
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/ 39

UNIT-II

Inheritance: Basics, Using Super, Creating Multilevel hierarchy, Method


overriding, Dynamic Method Dispatch, Using Abstract classes, Using final with
inheritance, Object class,
Packages: Basics, Finding packages and CLASSPATH, Access Protection,
Importing packages.
Interfaces: Definition, Implementing Interfaces, Extending Interfaces, Nested
Interfaces, Applying Interfaces, Variables in Interfaces.
Inheritance:
Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another. With the use of inheritance the
information is made manageable in a hierarchical order.
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 super class (base class, parent class).

extends Keyword:

extends is the keyword used to inherit the properties of a class.


Following is the syntax of extends keyword.
Syntax:
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}

Sample Code

Following is an example demonstrating Java inheritance. In this example, you can


observe two classes namely Calculation and MyCalculation.Using extends
keyword, the My_Calculation inherits the methods addition() and Subtraction() of
Calculation class.Copy and paste the following program in a file with name
My_Calculation.java
Example:
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

Using Super Keyword in Java

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.

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();
d.printColor();
}
}
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If
we print color property, it will print the color of current class by default. To access the
parent property, we need to use super keyword.

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

In the above example Animal and Dog both classes have eat() method
if we call eat() method from Dog class, it will call the eat() method of Dog class by
default because priority is given to local.

To call the parent class method, we need to use super keyword.

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

Note: super() is added in each class constructor automatically by compiler if there is no super() or
this().
Multilevel Hierarchy in java programming

In simple inheritance a subclass or derived class derives the properties from its
parent class, but in multilevel inheritance a subclass is derived from a derived class.
One class inherits only single class. Therefore, in multilevel inheritance, every time
ladder increases by one. The lower most class will have the properties of all the
super classes’.

It is common that a class is derived from another derived class. The class student
serves as a base class for the derived class marks, which in turn serves as a base
class for the derived class percentage. The class marks is known as intermediates
base class since it provides a link for the inheritance between student and
percentage.

The chain is known as inheritance path. When this type of situation occurs, each
subclass inherits all of the features found in all of its super classes. In this case,
percentage inherits all aspects of marks and student.

To understand the flow of program read all comments of program.

class student
{
int rollno;
String name;

student(int r, String n)
{
rollno = r;
name = n;
}
void dispdatas()
{
System.out.println("Rollno = " + rollno);
System.out.println("Name = " + name);
}
}

class marks extends student


{
int total;
marks(int r, String n, int t)
{
super(r,n); //call super class (student) constructor
total = t;
}
void dispdatam()
{
dispdatas(); // call dispdatap of student class
System.out.println("Total = " + total);
}
}

class percentage extends marks


{
int per;

percentage(int r, String n, int t, int p)


{
super(r,n,t); //call super class(marks) constructor
per = p;
}
void dispdatap()
{
dispdatam(); // call dispdatap of marks class
System.out.println("Percentage = " + per);
}
}
class Multi_Inhe
{
public static void main(String args[])
{
percentage stu = new percentage(102689, "Srilakshmi", 350, 70);

//call constructor percentage


stu.dispdatap(); // call dispdatap of percentage class
}
}

Output

G:\>javac Multi_Inhe.java
G:\>java Multi_Inhe
Rollno = 102689
Name = srilakshmi
Total = 350
Percentage = 70

Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method


that has been declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

o Method overriding is used to provide the specific implementation of a method


which is already provided by its superclass.

o Method overriding is used for runtime polymorphism


Rules for Java Method Overriding

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

2. The method must have the same parameter as in the parent class.

3. There must be an IS-A relationship (inheritance).

Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use
method overriding.

//Java Program to demonstrate why we need method overriding


//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}

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.

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 and parameter of
the method are the same, and there is IS-A relationship between the classes, so
there is method overriding.

//Java Program to illustrate the use of Java Method Overriding


//Creating a parent class.
class Vehicle{
//defining a method
void run(){
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Output:
Bike is running safely

A real example of Java Method Overriding

Consider a scenario where Bank is a class that provides functionality to get the rate
of interest. However, the rate of interest varies according to banks. For example,
SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of interest.
Dynamic method dispatch or Runtime Polymorphism :

Dynamic method dispatch is a mechanism by which a call to an overridden method


is resolved at runtime. This is how java implements runtime polymorphism. When
an overridden method is called by a reference, java determines which version of
that method to execute based on the type of object it refer to. In simple words the
type of object which it referred determines which version of overridden method will
be called.

Upcasting:
When Parent class reference variable refers to Child class object, it is known
as Upcasting

Example
class Game

public void type()

System.out.println("Indoor & outdoor"); }

Class Cricket extends Game

public void type()

{
System.out.println("outdoor game");

public static void main(String[] args)

Game gm = new Game();

Cricket ck = new Cricket();

gm.type();

ck.type();

gm=ck; //gm refers to Cricket object

gm.type(); //calls Cricket's version of type

Output:

Indoor & outdoor

Outdoor game

Outdoor game

Difference between Static binding and Dynamic binding in java ?

Static binding in Java occurs during compile time while dynamic binding occurs
during runtime. Static binding uses type(Class) information for binding while
dynamic binding uses instance of class(Object) to resolve calling of method at run-
time. Overloaded methods are bonded using static binding while overridden
methods are bonded using dynamic binding at runtime.

In simpler terms, Static binding means when the type of object which is invoking
the method is determined at compile time by the compiler. While Dynamic binding
means when the type of object which is invoking the method is determined at run
time by the compiler.
Abstract class in Java :

A class which is declared with the abstract keyword is known as an abstract class in
Java. It can have abstract and non-abstract methods (method with the body).

Before learning the Java abstract class, let's understand the abstraction in Java
first.

Abstraction in Java :

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you 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.

Ways to achieve Abstraction :

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)

2. Interface (100%)

Abstract class in Java :

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.

Points to Remember :

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

o It can have abstract and non-abstract methods.


o It cannot be instantiated.

o It can have constructors and static methods also.

o It can have final methods which will force the subclass not to change the
body of the method.

Example of abstract class :

abstract class A{}

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

Using final with Inheritance in Java:

final is a keyword in java used for restricting some functionalities. We can declare
variables, methods and classes with final keyword.

Using final with inheritance:

During inheritance, we must declare methods with final


keyword for which we required to follow the same implementation throughout all
the derived classes. Note that it is not necessary to declare final methods in the
initial stage of inheritance(base class always). We can declare final method in any
subclass for which we want that if any other class extends this subclass, then it
must follow same implementation of the method as in the that subclass.
EX1:
class Bike{
final void run(){
System. out. println("running...");
}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2(). run();
}
}
OUTPUT: running

EX2:
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Output:Compile Time Error

When a class is declared as final then it cannot be subclassed i.e. no any other
class can extend it. This is particularly useful, for example, when creating an
immutable class like the predefined String class. The following fragment
illustrates final keyword with a class:

final class A

// methods and fields

// The following class is illegal.


class B extends A

// ERROR! Can't subclass A

Note :

 Declaring a class as final implicitly declares all of its methods as final, too.
 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. For more on abstract classes, refer abstract classes in java

Object class in Java :

The Object class is the parent class of all the classes in java by default. In other
words, it is the topmost class of java.

The Object class is beneficial if you want to refer any object whose type you don't
know. Notice that parent class reference variable can refer the child class object,
know as upcasting.

Let's take an example, there is getObject() method that returns an object but it can
be of any type like Employee,Student etc, we can use Object class reference to
refer that object. For example:

1. Object obj=getObject();//we don't know what object will be returned from this method

The Object class provides some common behaviors to all the objects such as object
can be compared, object can be cloned, object can be notified etc.
Methods of Object class:

Method Description

public final Class getClass() returns the Class class object of this object. The
Class class can further be used to get the metadata
of this class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.

protected Object clone() throws creates and returns the exact copy (clone) of this
CloneNotSupportedException object.

public String toString() returns the string representation of this object.

public final void notify() wakes up single thread, waiting on this object's
monitor.

public final void notifyAll() wakes up all the threads, waiting on this object's
monitor.

public final void wait(long causes the current thread to wait for the specified
timeout)throws InterruptedException milliseconds, until another thread notifies (invokes
notify() or notifyAll() method).

public final void wait(long timeout,int causes the current thread to wait for the specified
nanos)throws InterruptedException milliseconds and nanoseconds, until another thread
notifies (invokes notify() or notifyAll() method).
public final void wait()throws causes the current thread to wait, until another
InterruptedException thread notifies (invokes notify() or notifyAll()
method).

protected void finalize()throws is invoked by the garbage collector before object is


Throwable being garbage collected.

Java Package :

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.

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

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

For example

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

The . represents the current folder.

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

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. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
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

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

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. }
Output:Hello

Note: If you import a package, subpackages will not be imported.

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.
Set CLASSPATH System Variable
To display the current CLASSPATH variable, use the following commands in Windows

 In Windows → C:\> set CLASSPATH


To delete the current contents of the CLASSPATH variable, use −

 In Windows → C:\> set CLASSPATH =


To set the CLASSPATH variable −

 In Windows → set CLASSPATH = C:\users\jack\java\classes.

HOW TO SET CLASS PATH IN JAVA:

CLASSPATH is an environment variable (i.e., global variables of the operating system


available to all the processes) needed for the Java compiler and runtime to locate the
Java packages/classes used in a Java program. (Why not call PACKAGEPATH?) This
is similar to another environment variable PATH, which is used by the Command shell
to find the executable programs.

CLASSPATH can be set in one of the following ways:

 CLASSPATH can be set permanently in the environment: In Windows, choose


control panel ⇒ System ⇒ Advanced ⇒ Environment Variables ⇒ choose
"System Variables" (for all the users) or "User Variables" (only the currently login
user) ⇒ choose "Edit" (if CLASSPATH already exists) or "New" ⇒ Enter
"CLASSPATH" as the variable name ⇒ Enter the required directories and JAR
files (separated by semicolons) as the value (e.g.,
".;c:\myProject\classes;d:\tomcat\lib\servlet-api.jar"). Take note that you need to
include the current working directory (denoted by '.') in the CLASSPATH.

Access Protection in JAVA:


You must have seen public, private and protected keywords while practising java
programs, these are called access modifiers. An access modifier restricts the
access of a class, constructor, data member and method in another class. In java
we have four access modifiers:
1. default
2. private
3. protected
4. public
1. Default access modifier
When we do not mention any access modifier, it is called default access modifier.
The scope of this modifier is limited to the package only. This means that if we
have a class with the default access modifier in a package, only those classes
that are in this package can access this class. No other class outside this
package can access this class. Similarly, if we have a default method or data
member in a class, it would not be visible in the class of another package. Lets
see an example to understand this:

Default Access Modifier Example in Java


To understand this example, you must have the knowledge of packages in java.

In this example we have two classes, Test class is trying to access the default
method of Addition class, since class Test belongs to a different package, this
program would throw compilation error, because the scope of default modifier is
limited to the same package in which it is declared.
Addition.java

package abcpackage;

public class Addition {


int addTwoNumbers(int a, int b){
return a+b;
}
}

Test.java

package xyzpackage;

import abcpackage.*;
public class Test {
public static void main(String args[]){
Addition obj = new Addition();
obj.addTwoNumbers(10, 21);
}
}

Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method addTwoNumbers(int, int) from the type Addition is not visible
at xyzpackage.Test.main(Test.java:12)

2. Private access modifier


The scope of private modifier is limited to the class only.

1. Private Data members and methods are only accessible within the class
2. Class and Interface cannot be declared as private
3. If a class has private constructor then you cannot create the object of that
class from outside of the class.

Let’s see an example to understand this:

Private access modifier example in java


This example throws compilation error because we are trying to access the
private data member and method of class ABC in the class Example. The private
data member and method are only accessible within the class.

class ABC{
private double num = 100;
private int square(int a){
return a*a;
}
}
public class Example{
public static void main(String args[]){
ABC obj = new ABC();
System.out.println(obj.num);
System.out.println(obj.square(10));
}
}
Output:

Compile - time error


3. Protected Access Modifier
Protected data member and method are only accessible by the classes of the
same package and the subclasses present in any package. You can also say
that the protected access modifier is similar to default access modifier with one
exception that it has visibility in sub classes.
Classes cannot be declared protected. This access modifier is generally used in
a parent child relationship.
Protected access modifier example in Java
In this example the class Test which is present in another package is able to call
the addTwoNumbers() method, which is declared protected. This is because the Test
class extends class Addition and the protected modifier allows the access of
protected members in subclasses (in any packages).
Addition.java

package abcpackage;
public class Addition {

protected int addTwoNumbers(int a, int b){


return a+b;
}
}
Test.java

package xyzpackage;
import abcpackage.*;
class Test extends Addition{
public static void main(String args[]){
Test obj = new Test();
System.out.println(obj.addTwoNumbers(11, 22));
}
}
Output:

33

4. Public access modifier


The members, methods and classes that are declared public can be accessed
from anywhere. This modifier doesn’t put any restriction on the access.

public access modifier example in java


Lets take the same example that we have seen above but this time the method
addTwoNumbers() has public modifier and class Test is able to access this
method without even extending the Addition class. This is because public
modifier has visibility everywhere.
Addition.java

package abcpackage;

public class Addition {


public int addTwoNumbers(int a, int b){
return a+b;
}
}
Test.java

package xyzpackage;
import abcpackage.*;
class Test{
public static void main(String args[]){
Addition obj = new Addition();
System.out.println(obj.addTwoNumbers(100, 1));
}
}
Output:

101
Lets see the scope of these access modifiers in tabular form:

The scope of access modifiers in tabular form


------------+-------+---------+--------------+--------------+--------
| Class | Package | Subclass | Subclass |Outside|
| | |(same package)|(diff package)|Class |
————————————+———————+—————————+——————————----+—————————----—+————————
public | Yes | Yes | Yes | Yes | Yes |
————————————+———————+—————————+—————————----—+—————————----—+————————
protected | Yes | Yes | Yes | Yes | No |
————————————+———————+—————————+————————----——+————————----——+————————
default | Yes | Yes | Yes | No | No |
————————————+———————+—————————+————————----——+————————----——+————————
private | Yes | No | No | No | No |
------------+-------+---------+--------------+--------------+--------

Interface in Java:

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.

In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body.
Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?

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.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total


abstraction; means all the methods in an interface are declared with the
empty body, and all the fields are public, static and final by default. A class
that implements an interface must implement all the methods declared in
the interface.

Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
Java 8 Interface Improvement

Since Java 8, interface can have default and static methods which is
discussed later.

Internal addition by the compiler


The Java compiler adds public and abstract keywords before the interface
method. Moreover, it adds public, static and final keywords before data
members.

In other words, Interface fields are public, static and final by default, and the
methods are public and abstract.

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.

Java Interface Example

In this example, the Printable interface has only one method, and its
implementation is provided in the A6 class.

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }

Output:

Hello

Java Interface Example: Drawable

In this example, the Drawable interface has only one method. Its
implementation is provided by Rectangle and Circle classes. In a real
scenario, an interface is defined by someone else, but its implementation is
provided by different implementation providers. Moreover, it is used by
someone else. The implementation part is hidden by the user who uses the
interface.

File: TestInterface1.java

1. //Interface declaration: by first user


2. interface Drawable{
3. void draw();
4. }
5. //Implementation: by second user
6. class Rectangle implements Drawable{
7. public void draw(){System.out.println("drawing rectangle");}
8. }
9. class Circle implements Drawable{
10. public void draw(){System.out.println("drawing circle");}
11. }
12. //Using interface: by third user
13. class TestInterface1{
14. public static void main(String args[]){
15. Drawable d=new Circle();//In real scenario, object is provided by met
hod e.g. getDrawable()
16. d.draw();
17. }}

Output: drawing circle

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 A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }
Output: Hello
Welcome

Java 8 Default Method in Interface

Since Java 8, we can have method body in interface. But we need to make it
default method. Let's see an example:

File: TestInterfaceDefault.java

1. interface Drawable{
2. void draw();
3. default void msg(){System.out.println("default method");}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8. class TestInterfaceDefault{
9. public static void main(String args[]){
10. Drawable d=new Rectangle();
11. d.draw();
12. d.msg();
13. }}

Output:

drawing rectangle
default method

Java 8 Static Method in Interface

Since Java 8, we can have static method in interface. Let's see an example:

File: TestInterfaceStatic.java

1. interface Drawable{
2. void draw();
3. static int cube(int x){return x*x*x;}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8.
9. class TestInterfaceStatic{
10. public static void main(String args[]){
11. Drawable d=new Rectangle();
12. d.draw();
13. System.out.println(Drawable.cube(3));
14. }}

Output:
drawing rectangle
27

Difference between abstract class and interface

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.

Abstract class Interface

1) Abstract class can have abstract and Interface can have only
non-abstract methods. abstract methods. Since Java
8, it can have default and
static methods also.

2) Abstract class doesn't support Interface supports multiple


multiple inheritance. inheritance.

3) Abstract class can have final, non- Interface has only static and
final, static and non-static variables. final variables.

4) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract
class.

5) The abstract keyword is used to The interface keyword is


declare abstract class. used to declare interface.

6) An abstract classcan extend another An interface can extend


Java class and implement multiple Java
interfaces. another Java interface only.

7) An abstract classcan be extended An interface class can be


using keyword "extends". implemented using keyword
"implements".

8) A Javaabstract classcan have class Members of a Java interface


members like private, protected, etc. are public by default.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Java Nested Interface:


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.

Syntax of nested interface:

interface interface_name{
...
interface nested_interface_name{
...
}
}

EXAMPLE1:
interface Showable{
void show();
interface Message{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message{
public void msg(){System.out.println("Hello nested interface");}

public static void main(String args[]){


Showable.Message message=new TestNestedInterface1();//upcasting here
message.msg();
}
}
Output: Hello nested interface

Multiple Interfaces:
To implement multiple interfaces, separate them with a comma:

Example:
interface FirstInterface {

public void myMethod(); // interface method

interface SecondInterface {

public void myOtherMethod(); // interface method

class DemoClass implements FirstInterface, SecondInterface {

public void myMethod() {

System.out.println("Some text..");

public void myOtherMethod() {


System.out.println("Some other text...");

class MyMainClass {

public static void main(String[] args) {

DemoClass myObj = new DemoClass();

myObj.myMethod();

myObj.myOtherMethod();

Output:
Some text...
Some other text..

You might also like