Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

BE Java Module-3

The document provides an overview of inheritance in Java, explaining its purpose, types, and advantages such as code reusability and polymorphism. It details the use of the 'super' keyword for accessing parent class methods and fields, as well as how to prevent inheritance using the 'final' keyword. Additionally, it covers access modifiers and their significance in controlling access to class members.

Uploaded by

varadaraj.navkis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

BE Java Module-3

The document provides an overview of inheritance in Java, explaining its purpose, types, and advantages such as code reusability and polymorphism. It details the use of the 'super' keyword for accessing parent class methods and fields, as well as how to prevent inheritance using the 'final' keyword. Additionally, it covers access modifiers and their significance in controlling access to class members.

Uploaded by

varadaraj.navkis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Inheritance:

Inheritance: It is the mechanism in Java by which one class is allowed to


inherit the features (fields and methods) of another class. In Java, Inheritance
means creating new classes based on existing ones. A class that inherits from
another class can reuse the methods and fields of that class.
Why Do We Need Java Inheritance?
• Code Reusability: The code written in the Superclass is common to all
subclasses. Child classes can directly use the parent class code.
• Method Overriding: Method Overriding is achievable only through
Inheritance. It is one of the ways by which Java achieves Run Time
Polymorphism.
• Abstraction: The concept of abstract where we do not have to provide all
details, is achieved through inheritance. Abstraction only shows the
functionality to the user.
Terminologies Used in Java Inheritance
• Class: Class is a set of objects which shares common characteristics/
behavior and common properties/ attributes. Class is not a real-world
entity. It is just a template or blueprint or prototype from which objects
are created.
• Super Class/Parent Class: The class whose features are inherited is
known as a superclass(or a base class or a parent class).
• Sub Class/Child Class: The class that inherits the other class is known
as a subclass(or a derived class, extended class, or child class). The
subclass can add its own fields and methods in addition to the superclass
fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when
we want to create a new class and there is already a class that includes
some of the code that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields and methods of the
existing class.
How to Use Inheritance in Java?
The extends keyword is used for inheritance in Java. Using the extends
keyword indicates you are derived from an existing class. In other words,
“extends” refers to increased functionality.
Syntax :
class DerivedClass extends BaseClass
{
//methods and fields
}
Inheritance Types
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
// Java program to illustrate the concept of single inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

// Parent class
class Parent {
public void printparent()
{
System.out.println("parent");
}
}
class Child extends Parent {
public void printchild() {
System.out.println("child");
}
}

public class SingleInheritance {


public static void main(String[] args)
{
Child obj = new Child();
obj.printparent();
obj.printchild();
obj.printparent();
}
}
Multilevel
// Importing required libraries
import java.io.*;
import java.lang.*;
import java.util.*;

// Parent class One


class GrandParent {

public void printGrandparent() {


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

// Child class Parent inherits from class GrandParent


class Parent extends GrandParent {
public void printparent() {
System.out.println("parent");
}
}

// Child class Child inherits from class Parent


class Child extends Parent {

public void printchild() {


System.out.println("child");
}
}
public class MultilevelInheritance {
public static void main(String[] args) {
// Creating an object of class Child
Child obj = new Child();

// Calling method from class GrandParent


obj.printGrandparent();

// Calling method from class Parent


obj.printparent();

// Calling method from class Child


obj.printchild();
}
}
Hierarchical Inheritance

// Java program to illustrate the


// concept of Hierarchical inheritance

class A {
public void print_A() { System.out.println("Class A"); }
}

class B extends A {
public void print_B() { System.out.println("Class B"); }
}

class C extends A {
public void print_C() { System.out.println("Class C"); }
}

class D extends A {
public void print_D() { System.out.println("Class D"); }
}

// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();

C obj_C = new C();


obj_C.print_A();
obj_C.print_C();

D obj_D = new D();


obj_D.print_A();
obj_D.print_D();
}
}

Multiple Inheritance: In Multiple inheritances, one class can have more than
one superclass and inherit features from all parent classes.
Please note that Java does not support multiple inheritances with classes.
In Java, we can achieve multiple inheritances only through Interfaces. In the
image below, Class C is derived from interfaces A and B.

// Java program to illustrate the


// concept of Multiple inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

interface One {
public void print_One();
}

interface Two {
public void print_Two();
}
interface Three extends One, Two {
public void print_One();
}
class Child implements Three {
@Override public void print_One()
{
System.out.println("One");
}

public void print_Two() { System.out.println("Two"); }


}

// Drived class
public class MultipleInheritance {
public static void main(String[] args)
{
Child c = new Child();
c.print_One();
c.print_Two();
c.print_One();
}
}
Advantages Of Inheritance in Java:
1. Code Reusability: Inheritance allows for code reuse and reduces the amount of code that
needs to be written. The subclass can reuse the properties and methods of the superclass,
reducing duplication of code.
2. Abstraction: Inheritance allows for the creation of abstract classes that define a common
interface for a group of related classes. This promotes abstraction and encapsulation, making
the code easier to maintain and extend.
3. Class Hierarchy: Inheritance allows for the creation of a class hierarchy, which can be used to
model real-world objects and their relationships.
4. Polymorphism: Inheritance allows for polymorphism, which is the ability of an object to take
on multiple forms. Subclasses can override the methods of the superclass, which allows them
to change their behavior in different ways.
Disadvantages of Inheritance in Java:
1. Complexity: Inheritance can make the code more complex and harder to understand. This is
especially true if the inheritance hierarchy is deep or if multiple inheritances is used.
2. Tight Coupling: Inheritance creates a tight coupling between the superclass and subclass,
making it difficult to make changes to the superclass without affecting the subclass.

Self-assessment program
Create a base class containing the data members roll number and name. Also create a
member function to read and display the data using the concept of single level
inheritance. Create a derived class that contains marks of two subjects and total marks
as the data members
Member access rules
Access modifiers help to restrict the scope of a class, constructor, variable,
method, or data member. It provides security, accessibility, etc to the user
depending upon the access modifier used with the element.
Types of Access Modifiers in Java
There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public

1. Default Access Modifier


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. The data members,
classes, or methods that are not declared using any access modifiers i.e. having
default access modifiers are accessible only within the same package.

2. Private Access Modifier


The private access modifier is specified using the keyword private. The
methods or data members declared as private are accessible only within the
class in which they are declared.
• Any other class of the same package will not be able to access these
members.
• Top-level classes or interfaces can not be declared as private because
o private means “only visible within the enclosing class”.
o protected means “only visible within the enclosing class and any
subclasses”
3. Protected Access Modifier
• The protected access modifier is specified using the keyword protected.
• The methods or data members declared as protected are accessible within
the same package or subclasses in different packages.

4. Public Access modifier


The public access modifier is specified using the keyword public.
• The public access modifier has the widest scope among all other access
modifiers.
• Classes, methods, or data members that are declared as public
are accessible from everywhere in the program. There is no restriction
on the scope of public data members.

Important Points:
• If other programmers use your class, try to use the most restrictive access
level that makes sense for a particular member. Use private unless you
have a good reason not to.
• Avoid public fields except for constants.

Super keyword: Super keyword in java is a reference variable that is used to


refer to parent class when working with objects.
Characteristics of Super Keyword in Java
In Java, super keyword is used to refer to the parent class of a subclass. Here are
some of its key characteristics:
• super is used to call a superclass constructor: When a subclass is
created, its constructor must call the constructor of its parent class. This is
done using the super() keyword, which calls the constructor of the parent
class.
• super is used to call a superclass method: A subclass can call a method
defined in its parent class using the super keyword. This is useful when
the subclass wants to invoke the parent class’s implementation of the
method in addition to its own.
• super is used to access a superclass field: A subclass can access a field
defined in its parent class using the super keyword. This is useful when
the subclass wants to reference the parent class’s version of a field.
• super must be the first statement in a constructor: When calling a
superclass constructor, the super() statement must be the first statement in
the constructor of the subclass.
• super cannot be used in a static context: The super keyword cannot be
used in a static context, such as in a static method or a static variable
initializer.
• super is not required to call a superclass method: While it is possible
to use the super keyword to call a method in the parent class, it is not
required. If a method is not overridden in the subclass, then calling it
without the super keyword will invoke the parent class’s implementation.
Overall, the super keyword is a powerful tool for subclassing in Java, allowing
subclasses to inherit and build upon the functionality of their parent classes.
Use of super keyword in Java
It is majorly used in the following contexts as mentioned below:
• Use of super with Variables
• Use of super with Methods
• Use of super with Constructors
1. Use of super with Variables
This scenario occurs when a derived class and base class have the same data
members.
// super keyword in java example
// Base class vehicle
class Vehicle {
int maxSpeed = 120;
}

// sub class Car extending vehicle


class Car extends Vehicle {
int maxSpeed = 180;

void display()
{
// print maxSpeed of base class (vehicle)
System.out.println("Maximum Speed: "+ super.maxSpeed);
}
}

// Driver Program
class SuperTest {
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}

2. Use of super with Methods


This is used when we want to call the parent class method. So whenever a
parent and child class have the same-named methods then to resolve ambiguity
we use the super keyword.
// super keyword in java example
// superclass Person
class Person {
void message()
{
System.out.println("This is person class\n");
}
}
// Subclass Student
class Student extends Person {
void message()
{
System.out.println("This is student class");
}
// Note that display() is only in Student class
void display()
{
// will invoke or call current class message() method
message();

// will invoke or call parent class message() method


super.message();
}
}
class SuperMethodTest {
public static void main(String args[])
{
Student s = new Student();

// calling display() of Student


s.display();
}
}

3. Use of super with constructors


The super keyword can also be used to access the parent class constructor. One
more important thing is that ‘super’ can call both parametric as well as non-
parametric constructors depending on the situation.
// Java Code to show use of
// super keyword with constructor

// superclass Person
class Person {
Person()
{
System.out.println("Person class Constructor");
}
}
// subclass Student extending the Person class
class Student extends Person {
Student()
{
// invoke or call parent class constructor
super();

System.out.println("Student class Constructor");


}
}

// Driver Program
class SuperConstructorTest {
public static void main(String[] args)
{
Student s = new Student();
}
}

Advantages of Using Java Super Keyword


The super keyword in Java provides many advantages in object-oriented
programming are as follows:
• Enables reuse of code: Using the super keyword allows subclasses to
inherit functionality from their parent classes, which promotes the reuse
of code and reduces duplication.
• Supports polymorphism: Because subclasses can override methods and
access fields from their parent classes using super, polymorphism is
possible. This allows for more flexible and extensible code.
• Provides access to parent class behaviour: Subclasses can access and
use methods and fields defined in their parent classes through the super
keyword, which allows them to take advantage of existing behaviour
without having to reimplement it.
• Allows for customization of behaviour: By overriding methods and
using super to call the parent implementation, subclasses can customize
and extend the behaviour of their parent classes.
• Facilitates abstraction and encapsulation: The use of super promotes
encapsulation and abstraction by allowing subclasses to focus on their
behaviour while relying on the parent class to handle lower-level details.

Preventing inheritance
There are 2 ways to stop or prevent inheritance in Java programming. By using
final keyword with a class or by using a private constructor in a class.
Problem Statement: Let’s say we have a class A and we don’t want to allow
any other class to be derived from it. What are the possible solutions?
Using final keyword before a class declaration we can stop a class to be
inherited by other classes. For example,
public final class A
{

}
If we try to extend the class A which is final, compiler will flash an error i.e.
“The Type B cannot the subclass the final Class A”, if class B is trying to
extend final class A.
public class B extends A{//Error :The Type B cannot the subclass the Final
Class A
}

We can also stop a class to be extended/inherited by other classes in Java by


making the class constructor private.
If we make the class constructor private we’ll not be able to create the object of
this class from outside of this class. But, our purpose is to just prevent a class to
be inherited and not to stop object creation. Hence, we need a method that can
create an object of this class and return it.

We need to put a static method that will create and return an object. Why Static
method? Because, from outside of a class, to call a normal method we need an
object of the class, but, as constructor is private, we cannot create an object,
hence, only solution is to have a static method that can be called using class
name.
So, as a solution to stop a class to be extended, we need to make a constructor
private and have one static method that will create an object of this class and
return it.
class A {
// Make constructor private to prevent object creation
//From outside of this class.
private A() {
}
//Static method to create and return an object.
//this method will be called from outside by using
//class name only.
public static A GetInstance() {
return new A();
}
}
Final classes and methods
final is a keyword in java used for restricting some functionalities. We can
declare variables, methods, and classes with the final keyword.
Using final with inheritance
During inheritance, we must declare methods with the final keyword for which
we are 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 a final method in any subclass
for which we want that if any other class extends this subclass, then it must
follow the same implementation of the method as in that subclass.
The object class and its methods
Object class is present in java.lang package. Every class in Java is directly or
indirectly derived from the Object class. If a class does not extend any other
class then it is a direct child class of Object and if extends another class then it
is indirectly derived. Therefore the Object class methods are available to all
Java classes. Hence Object class acts as a root of the inheritance hierarchy in
any Java Program.

Polymorphism
The word polymorphism means having many forms. In simple words, we can
define Java Polymorphism as the ability of a message to be displayed in more
than one form.
Real-life Illustration of Polymorphism in Java: A person at the same time can
have different characteristics. Like a man at the same time is a father, a husband,
and an employee. So the same person possesses different behaviors in different
situations. This is called polymorphism.
Types of Java Polymorphism
In Java Polymorphism is mainly divided into two types:
• Compile-time Polymorphism
• Runtime Polymorphism
Compile-Time Polymorphism in Java
It is also known as static polymorphism. This type of polymorphism is achieved
by function overloading or operator overloading.
Note: But Java doesn’t support the Operator Overloading.

Method Overloading
When there are multiple functions with the same name but different parameters
then these functions are said to be overloaded. Functions can be overloaded by
changes in the number of arguments or/and a change in the type of arguments.
class Helper {
// Method with 2 integer parameters
static int Multiply(int a, int b)
{
// Returns product of integer numbers
return a * b;
}
// Method 2 With same name but with 2 double parameters
static double Multiply(double a, double b)
{
// Returns product of double numbers
return a * b;
}
}
Runtime Polymorphism in Java
It is also known as Dynamic Method Dispatch. It is a process in which a
function call to the overridden method is resolved at Runtime. This type of
polymorphism is achieved by Method Overriding. Method overriding, on the
other hand, occurs when a derived class has a definition for one of the member
functions of the base class. That base function is said to be overridden.

Dynamic binding
Static vs Dynamic Binding in Java
• private, final and static members (methods and variables) use static
binding while for virtual methods (In Java methods are virtual by default)
binding is done during run time based upon the run time object.
• The static binding uses Type information for binding while Dynamic
binding uses Objects to resolve to bind.
• Overloaded methods are resolved (deciding which method to be called
when there are multiple methods with the same name) using static
binding while overridden methods use dynamic binding, i.e, at run time.

Static Binding
The binding which can be resolved at compile time by the compiler is known as
static or early binding. The binding of all the static, private, and final methods is
done at compile-time.
// Java Program to Illustrate Static Binding

// Main class
class NewClass {

// Static nested inner class


// Class 1
public static class superclass {

// Method of inner class


static void print()
{
// Print statement
System.out.println(
"print() in superclass is called");
}
}

// Static nested inner class


// Class 2
public static class subclass extends superclass {

// Method of inner class


static void print()
{

// print statement
System.out.println(
"print() in subclass is called");
}
}

// Method of main class


// Main driver method
public static void main(String[] args)
{

// Creating objects of static inner classes


// inside main() method
superclass A = new superclass();
superclass B = new subclass();

// Calling method over above objects


A.print();
B.print();
}
}

Output
print() in superclass is called
print() in superclass is called

Output Explanation: As you can see, in both cases the print method of the
superclass is called. Let us discuss how this happens
• We have created one object of subclass and one object of the superclass
with the reference of the superclass.
• Since the print method of the superclass is static, the compiler knows that
it will not be overridden in subclasses and hence compiler knows during
compile time which print method to call and hence no ambiguity.

Dynamic Binding
In Dynamic binding compiler doesn’t decide the method to be called.
Overriding is a perfect example of dynamic binding. In overriding both parent
and child classes have the same method.

// Java Program to Illustrate Dynamic Binding


// Main class
public class DynamicBinding {

// Static nested inner class


// Class 1
public static class superclass {

// Method of inner class 1


void print()
{

// Print statement
System.out.println("print in superclass is called");
}
}

// Static nested inner class


// Class 2
public static class subclass extends superclass {

// Method of inner class 2


@Override void print()
{

// Print statement
System.out.println("print in subclass is called");
}
}

// Method inside main class


public static void main(String[] args)
{

// Creating object of inner class 1


// with reference to constructor of super class
superclass A = new superclass();

// Creating object of inner class 1


// with reference to constructor of sub class
superclass B = new subclass();

// Calling print() method over above objects


A.print();
B.print();
}
}

Output
print in superclass is called
print in subclass is called
Output Explanation:
• Methods are not static in this code.
• During compilation, the compiler has no idea as to which print has to be
called since the compiler goes only by referencing variable not by the
type of object, and therefore the binding would be delayed to runtime and
therefore the corresponding version of the print will be called based on
type on an object.

Static Binding Dynamic Binding

It takes place at compile time for which It takes place at runtime so do it is


is referred to as early binding referred to as late binding.

It uses overloading more precisely


It uses overriding methods.
operator overloading method
Static Binding Dynamic Binding

It takes place using virtual


It takes place using normal functions
functions

Static or const or private functions use


Real objects use dynamic binding
real objects in static binding

Method overriding
Overriding is a feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its super-classes
or parent classes. When a method in a subclass has the same name, the same
parameters or signature, and the same return type(or sub-type) as a method in its
super-class, then the method in the subclass is said to override the method in the
super-class.

Method overriding is one of the ways by which Java achieves Run Time
Polymorphism. The version of a method that is executed will be determined by
the object that is used to invoke it. If an object of a parent class is used to
invoke the method, then the version in the parent class will be executed, but if
an object of the subclass is used to invoke the method, then the version in the
child class will be executed. In other words, it is the type of the object being
referred to (not the type of the reference variable) that determines which version
of an overridden method will be executed.

// Java program to demonstrate method overriding in java

// Base Class
class Parent {
void show() { System.out.println("Parent's show()"); }
}

// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override void show()
{
System.out.println("Child's show()");
}
}

// Driver class
class Main {
public static void main(String[] args)
{
// If a Parent type reference refers to a Parent object, then Parent's
// show is called
Parent obj1 = new Parent();
obj1.show();

// If a Parent type reference refers to a Child object Child's show()


// is called. This is called RUN TIME POLYMORPHISM.
Parent obj2 = new Child();
obj2.show();
}
}

Rules for Java Method Overriding


1. Overriding and Access Modifiers
2. Final methods can not be overridden
3. Static methods can not be overridden(Method Overriding vs Method
Hiding):
4. Private methods can not be overridden
5. The overriding method must have the same return type (or subtype)
6. Invoking overridden method from sub-class

Abstract classes and methods


Abstract class is declared with the abstract keyword. It may have both abstract
and non-abstract methods (methods with bodies). An abstract is a Java modifier
applicable for classes and methods in Java but not for Variables.

Java abstract class is a class that can not be initiated by itself, it needs to be
subclassed by another class to use its properties. An abstract class is declared
using the “abstract” keyword in its class definition.

Illustration of Abstract class


abstract class Shape
{
int color;
// An abstract function
abstract void draw();
}

In Java, the following some important observations about abstract classes are as
follows:
1. An instance of an abstract class can not be created.
2. Constructors are allowed.
3. We can have an abstract class without any abstract method.
4. There can be a final method in abstract class but any abstract method in
class(abstract class) can not be declared as final or in simpler terms final
method can not be abstract itself as it will yield an error: “Illegal
combination of modifiers: abstract and final”
5. We can define static methods in an abstract class
6. We can use the abstract keyword for declaring top-level classes (Outer
class) as well as inner classes as abstract
7. If a class contains at least one abstract method then compulsory should
declare a class as abstract
8. If the Child class is unable to provide implementation to all abstract
methods of the Parent class then we should declare that Child class as
abstract so that the next level Child class should provide implementation
to the remaining abstract method

// Abstract class
abstract class Sunstar {
abstract void printInfo();
}

// Abstraction performed using extends


class Employee extends Sunstar {
void printInfo()
{
String name = "Raj";
int age = 24;
float salary = 5000.2F;

System.out.println(name);
System.out.println(age);
System.out.println(salary);
}
}

// Base class
class Base {
public static void main(String args[])
{
Sunstar s = new Employee();
s.printInfo();
}
}

Abstract Class having constructor, data member, and methods


Elements abstract class can have
• data member
• abstract method
• method body (non-abstract method)
• constructor
• main() method.

// Java Program to implement Abstract Class


// having constructor, data member, and methods
import java.io.*;

abstract class Subject {


Subject() {
System.out.println("Learning Subject");
}

abstract void syllabus();

void Learn(){
System.out.println("Preparing Right Now!");
}
}

class IT extends Subject {


void syllabus(){
System.out.println("C , Java , C++");
}
}

class Abstract {
public static void main(String[] args) {
Subject x=new IT();

x.syllabus();
x.Learn();
}
}
Object Class:
There is one special class, Object, defined by java. All other classes are
subclasses of Object.
Object is a superclass of all other classes. i.e reference variable of type Object
can refer to an object of any other class. Also, since arrays are implemented as
classes, a variable of type Object can also refer to any array.
Object defines the following methods, which means that they are available in
every object.
Method Purpose
object clone() Creates a new object that is the same as the object being
cloned.
boolean Determines whether one object is equal to another.
equals(Object object)
void finalize() Called before an unused object is recycled.
Class getClass() Obtains the class of an object at run time.
int hashCode() Returns the hash code associated with the invoking object.
void notify() Resumes execution of a thread waiting on the invoking object
void notifyAll() Resumes execution of all threads waiting on the invoking
object.
String toString() Returns a string that describes the object.
void wait() Waits on another thread of execution.
void wait(long
milliseconds)
void wait(long
milliseconds, int
nanaosecons)

The methods getClass(), notify(), notifyAll() and wait() are declared as final.
equals() method compares the contents of two objects. It returns true if the
objects are equivalent, and false otherwise.
toString() method returns a string that contains a description of the object on
which it is called. Also, this method is automatically called when an object is
output using println().
Interfaces: Interfaces, Default Interface Methods, Use Static Methods in an
interface, private interface methods

Interface: Interface is a keyword. 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.

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:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}

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.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

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.

//Interface declaration: by first user


interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method
e.g. getDrawable()
d.draw();
}}

Use Static Methods in an interface:


Static Methods in Interface are those methods, which are defined in the
interface with the keyword static. Unlike other methods in Interface, these static
methods contain the complete definition of the function and since the definition
is complete and the method is static, therefore these methods cannot be
overridden or changed in the implementation class.
// Java program to demonstrate static method in Interface.

interface NewInterface {
// static method
static void hello()
{
System.out.println("Hello, New Static Method Here");
}
// Public and abstract method of Interface
void overrideMethod(String str);
}

// Implementation Class
public class InterfaceDemo implements NewInterface {
public static void main(String[] args)
{
InterfaceDemo interfaceDemo = new InterfaceDemo();

// Calling the static method of interface


NewInterface.hello();

// Calling the abstract method of interface


interfaceDemo.overrideMethod("Hello, Override Method
here");
}

// Implementing interface method


@Override
public void overrideMethod(String str)
{
System.out.println(str);
}
}

Output:
Hello, New Static Method Here
Hello, Override Method here
private interface methods

Java 9 onwards, you can include private methods in interfaces. Before Java 9 it
was not possible.

In Java SE 7 or earlier versions, an interface can have only two things


i.e. Constant variables and Abstract methods.

Java 8 Interface Changes


Some new features to interface were introduced in Java 8 i.e. Default methods
and Static methods feature. In Java 8, an interface can have only four types:
1. Constant variables
2. Abstract methods
3. Default methods
4. Static methods

Java 9 Interface Changes


Java 9 introduced private methods and private static method in interfaces. In
Java 9 and later versions, an interface can have six different things:
1. Constant variables
2. Abstract methods
3. Default methods
4. Static methods
5. Private methods
6. Private Static methods

These private methods will improve code re-usability inside interfaces and will
provide choice to expose only our intended methods implementations to
users.These methods are only accessible within that interface only and cannot
be accessed or inherited from an interface to another interface or class.

// Java 9 program to illustrate


// private methods in interfaces
public interface TempI {
public abstract void mul(int a, int b);
public default void add(int a, int b)
{
// private method inside default method
sub(a, b);
// static method inside other non-static method
div(a, b);
System.out.print("Answer by Default method = ");
System.out.println(a + b);
}

public static void mod(int a, int b)


{
div(a, b); // static method inside other static method
System.out.print("Answer by Static method = ");
System.out.println(a % b);
}
private void sub(int a, int b)
{
System.out.print("Answer by Private method = ");
System.out.println(a - b);
}
private static void div(int a, int b)
{
System.out.print("Answer by Private static method = ");
System.out.println(a / b);
}
}
class Temp implements TempI {
@Override
public void mul(int a, int b)
{
System.out.print("Answer by Abstract method = ");
System.out.println(a * b);
}
public static void main(String[] args)
{
TempI in = new Temp();
in.mul(2, 3);
in.add(6, 2);
TempI.mod(5, 3);
}
}

Output
Answer by Abstract method = 6 // mul(2, 3) = 2*3 = 6
Answer by Private method = 4 // sub(6, 2) = 6-2 = 4
Answer by Private static method = 3 // div(6, 2) = 6/2 = 3
Answer by Default method = 8 // add(6, 2) = 6+2 = 8
Answer by Private static method = 1 // div(5, 3) = 5/3 = 1
Answer by Static method = 2 // mod(5, 3) = 5%3 = 2
Rules For using Private Methods in Interfaces
• Private interface method cannot be abstract and no private and
abstract modifiers together.
• Private method can be used only inside interface and other static
and non-static interface methods.
• Private non-static methods cannot be used inside private static
methods.
• We should use private modifier to define these methods and no
lesser accessibility than private modifier.

You might also like