[Go to site: main page, start]

0% found this document useful (0 votes)
10 views74 pages

Java Inheritance and Interfaces Guide

This syllabus covers the concepts of inheritance and interfaces in Java, detailing single inheritance, polymorphism, and member access rules. It explains the benefits of inheritance, including code reusability and information hiding, and outlines various types of inheritance such as single, multilevel, hierarchical, and hybrid. Additionally, it discusses the use of the super keyword, polymorphism, method overriding, and dynamic method dispatch.
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)
10 views74 pages

Java Inheritance and Interfaces Guide

This syllabus covers the concepts of inheritance and interfaces in Java, detailing single inheritance, polymorphism, and member access rules. It explains the benefits of inheritance, including code reusability and information hiding, and outlines various types of inheritance such as single, multilevel, hierarchical, and hybrid. Additionally, it discusses the use of the super keyword, polymorphism, method overriding, and dynamic method dispatch.
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

UNIT 2 Syllabus

UNIT II
Inheritance –Definition, single inheritance, benefits of inheritance, Member
access rules, super class,
polymorphism- method overriding, Dynamic method dispatch, using final with
inheritance, abstract classes,
Base class object.

Interfaces: definition, variables and methods in interfaces, differences between


classes and interfaces,
usage of implements and extends keyword, interfaces, uses of interfaces,
packages Applications: Extending the banking operations to the loan applicants.
Definition Inheritance
 Inheritance is the process of acquiring the properties by the sub class ( or
derived class or child class) from the super class (or base class or parent
class).

 When a child class(newly defined abstraction) inherits(extends) its


parent class (being inherited abstraction), all the properties and methods
of parent class becomes the member of child class.

 In addition, child class can add new data fields(properties) and


behaviors(methods), and

 It can override methods that are inherited from its parent class.
Inheritance Basics
The key word extends is used to define inheritance in Java.

Syntax:-

class subclass-name extends superclass-name {


// body of the class
}
Single Inheritance
-Derivation of a class from only one base class is called single inheritance.

//base class:
class A{ A
//members of A
}
//Derived class syntax: B

class B extends A{
//members of B
}
// Java Program to illustrate Inheritance

import [Link].*;

// Base or Super Class


class Employee {
int salary = 60000;
}

// Inherited or Sub Class


class Engineer extends Employee {
int benefits = 10000;
}

// Driver Class
class Gfg {
public static void main(String args[])
{
Engineer E1 = new Engineer();
[Link]("Salary : " + [Link]+ "\nBenefits : “
+[Link]);
}
}
The Benefits of Inheritance
 Software Reusability ( among projects )
 Code ( class/package ) can be reused among the projects.
 Ex., code to insert a new element into a table can be written once and
reused.

 Code Sharing ( within a project )


 It occurs when two or more classes inherit from a single parent class.
 This code needs to be written only once and will contribute only once to
the size of the resulting program.

 Increased Reliability (resulting from reuse and sharing of code)


 When the same components are used in two or more applications, the
bugs can be discovered more quickly.
 Information Hiding
 The programmer who reuses a software component needs only to
understand the nature of the component and its interface.
 It is not necessary for the programmer to have detailed information such
as the techniques used to implement the component.

 Rapid Prototyping (quickly assemble from pre-existing components)


 Software systems can be generated more quickly and easily by
assembling preexisting components.
 This type of development is called Rapid Prototyping.

 Consistency of Interface(among related objects )


 When two or more classes inherit from same superclass, the behavior they
inherit will be the same.
 Thus , it is easier to guarantee that interfaces to similar objects are
similar.
 Software Components
 Inheritance enables programmers to construct reusable components.

 Polymorphism and Frameworks (high-level reusable components)


 Normally, code reuse decreases as one moves up the levels of
abstraction.

 Lowest-level routines may be used in several different projects, but


higher-level routines are tied to a particular application.

 Polymorphism in programming languages permits the programmer to


generate high-level reusable components that can be tailored to fit
different applications by changes in their low-level parts.
Types of inheritance :-
There are five types of inheritance in java
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance
5. Hybrid Inheritance
Types of Inheritance

//Single Inheritance

class A{
}
class B extends A{
}

//Multilevel Inheritance

class A{
}
class B extends A{
}
class C extends B{
}
//Hierarchical Inheritance

class X{
}
class B extends X{
}
class C extends X{
}

//Multiple Inheritance

class A{
}
class B {
}
class C extends A , B
{
} //Wrong code
➢ Multiple Inheritance can be implemented by implementing multiple
interfaces not by extending multiple classes.
Example :
//Multiple Inheritance
class B extends A implements C , D
interface one{
{
}
} OK interface two{
}
class A implements one, two{
}

class C extends A extends B


{ class C extends A ,B {

} } WRONG
Hybrid inheritance:-
▪Hybrid is combination of hierarchical & multiple inheritance .
▪Java is not supporting hybrid inheritance
because multiple inheritance(not supported by java)
is included in hybrid inheritance.
class A {
A() {
[Link] ("Inside A's constructor.");
} C
} B
class B extends A { A
B() {
[Link]("Inside B's constructor.");
}
}
class C extends B {
C() { oc
[Link]("Inside C's constructor.");
}
}
class CallingCons A Output:
{ public static void main(String args[])
{ Inside A’s constructor
C oc = new C(); Inside B’s constructor
oaa
Inside C’s constructor
}
}
Super Keyword
 Subclass refers to its immediate super class by using super keyword.
• super has two general forms.
• First it calls the super class constructor.
• Second is used to access a member of the super class that has been
hidden by a member of a subclass.
Super keyword:-
Super keyword is holding super class object. And it is representing
▪Super class variables
▪Super class methods
Super class constructors
 Using super to call super class constructors
super (parameter-list);
• parameter-list specifies any parameters needed by the constructor in the
super class.
• super( ) must always be the first statement executed inside a subclass
constructor.
Super keyword required:-
class Parent
[Link](super.a+super.
{
b); //super class variables
int a=10,b=20; //instance variables
addition
};
class Child extends Parent
{ //instance variables
int a=100; public static void main(String[] args)
int b=200; { Child c = new Child();
void m1(int a,int b) c.m1(1000,2000);
//local variables }
{ };
[Link](a+b); //In above example sub class and
//local variables addition super class having same variable
[Link](this.a+this.b); names hence to represent.
//current class variables addition //a)sub class variables use this
} keyword.
//b)Super class variables use super
keyword.
super class and sub class contains methods with same names

class Parent
{ Ex.Program2:
void m1(int a)
{ class Parent
[Link]("parent m1()-->"+a); } { void m1() {
}; [Link]("parent m1() method");}
class Child extends Parent };
{
void m1(int a) class Child extends Parent
{ {
[Link]("child m1()-->"+a); void m1()
} {
void m2() [Link]("child class m1() method");}
{ void m3()
this.m1(10);//child class m1(int) method { this.m1();//current class method is executed
calling super.m1();//super class method will be
[Link]("child m2()"); executed
super.m1(100);// parent class m1(int) }
method calling public static void main(String[] args)
} { new Child().m3();
public static void main(String[] args) }
{ Child c = new Child(); c.m2(); };
}
// Using super to overcome name hiding.
class A {
int i;
}
class B extends A // Create a subclass by
extending class A.
{ int i; // this i hides the i in
A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
[Link]("i in superclass: " + super.i);
[Link]("i in subclass: " + i);
}
}
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
[Link](); This program displays the following:
} i in superclass: 1
} i in subclass: 2
Example:- To call super class constructor use super keyword.

class Parent public static void main(String[] args)


{ Parent() { Child c = new Child();
{ }//end class
[Link]("parent 0-arg };//end main
constructor");}
}; Note:
class Child extends Parent Child()
{ Child() { this(10); (must be first line)
{ this(10); //current class 1-arg [Link]("Child 0-arg
constructor calling constructor");
[Link]("Child 0-arg constructor"); }
} Child(int a)
Child(int a) { super(); (must be first line)
{ super(); //super class 0-arg [Link]("child 1-arg
constructor calling const-->"+a);
[Link]("child 1-arg constr->"+a); }
} •
Member access rules
Type of Access Level in Inheritance:
There are four access modifiers: private, public, protected, and package-level.
The absence of the private, public, and protected access modifier is the default or package-level
access.

Level Who can access Rule

private no access to the If a class member is declared private, it is


outside world accessible only inside the class that declares it.
A private class member is not inherited by
subclasses of that class.
public everyone A subclass inherits all public members of its
superclass.
protected subclasses A protected class member is accessible inside
the body of a subclass from the same package
as the class or in a different package.
default or package package-level class member is inherited only if
package-level the superclass and subclass are in the same
access package.
Member access rules
A subclass includes all of the members (default, public, protected) of its
superclass except private members.
class A{ class Protected{
private int v=10; public static void main(String args[]){
int d=20; B b=new B();
public int b=30; [Link]();
protected int p=40; C c=new C();
} [Link]();
class B extends A{ }
void disp(){ }
//[Link](“v value : "+v);
[Link](“d value : "+d);
[Link](“b value : "+b);
[Link]("p value : "+p);
} Output:
} d value : 20
class C extends B{
void show(){ b value : 30
[Link]("p value : "+p); p value : 40
} p value : 40
}
Polymorphism
• Polymorphism:-
➢ One thing can exhibits more than one form is called polymorphism.

➢ Polymorphism shows some functionality(method name same) with different logics


execution.

➢ The ability to appear in more forms is called polymorphism.

➢ Polymorphism is a Greek word poly means many and morphism means forms.
There are two types of polymorphism in java

➢ Compile time polymorphism / static binding / early binding


[method execution decided at compilation time] Example :- method overloading.
➢ Runtime polymorphism /dynamic binding /late binding.
[Method execution decided at runtime].
Example :- method overriding.
Compile time polymorphism [Method Overloading]:-
If java class allows two methods with same name but different number of
arguments such type of methods are called overloaded methods.
We can overload the methods in two ways in java language
By passing different number of arguments to the same methods.
void m1(int a){ }
void m1(int a,int b){ }
Provide the same number of arguments with different data types.
void m1(int a){ } void m1(char ch){ }
If we want achieve overloading concept one class is enough.
It is possible to overload any number of methods in single java class.
void m1(int a){ }
void m1(int a,int b){ }
void m1(int a){ }
void m1(char ch){ }
If we want achieve overloading concept one class is enough.
It is possible to overload any number of methods in single java class.
Method overloading:-
Example:-
class Test
{ //below three methods are overloaded methods.
void m1(char ch)
{[Link](" char-arg constructor "); }
void m1(int i)
{[Link]("int-arg constructor "); }
void m1(int i,int j)
{[Link](i+j); }
public static void main(String[] args)
{Test t=new Test();
t.m1('a'); t.m1(10); t.m1(10,20); //three methods execution decided at compilation
}
Method overriding(Runtime
polymorphism)
• If we want to achieve method overriding we need two class
with parent and child relationship.
• The parent class method contains some implementation
(logics).
– If child is satisfied use parent class method.
– If the child class not satisfied (required own implementation)
then override the method in Child class.
• A subclass has the same method as declared in the super
class it is known as method overriding.
• The parent class method is called ===> overridden
method
• The child class method is called ===> overriding method
• While overriding methods must fallow these rules:-
1. While overriding child class method signature &
parent class method signatures must be same
otherwise we are getting compilation error.
2. The return types of overridden method & overriding
method must be same.
3. While overriding check the modifiers permission like
the sub class method modifier is having same
permission or increasing level of parent class method
bur not decreasing order.
4. You are unable to override final methods. (Final
methods are preventing overriding).
5. While overriding check the covariant-return types.
6. Static methods are bounded with class hence we are
unable to override static methods.
• Example-1 :-method Overriding
class Parent //parent class
{
void property()
{
[Link]("money+land+hhouse");
}
void marry()
{[Link]("black girl"); } //overridden method
};
class Child extends Parent //child class
{
void marry()
{
[Link]("white girl/red girl");} //overriding method
public static void main(String[] args)
{
Child c=new Child();
[Link]();
[Link]();
Parent p=new Parent();
[Link]();
[Link]();
}
};
A Superclass Variable Can Reference a Subclass Object
• When a reference to a subclass object is assigned to a superclass variable, you
will have access only to those parts of the object defined by the superclass.
Ex:
class A{
int i=10;
}
class B extends A{
int j=30;
}
class Test{
public static void main(String args[]){
A a=new A();
B b=new B();
a=b;
[Link](a.i);
[Link](a.j);
}
}
Dynamic Method Dispatch
➢ Dynamic Method Dispatch is another name for Runtime
polymorphism in Java which originates with the concept of
method overriding. In this case, the call to an overridden method
will be resolved at the time of code execution (runtime) rather
than the compile time.
➢ Dynamic method dispatch in Java is a mechanism that helps to call an
overridden method at runtime by creating referenced objects. It is the
same as runtime polymorphism.
➢ Dynamic method dispatch in Java uses upcasting. Upcasting is a process
to convert the reference variable of the child class to the reference
variable of the parent class. Let us understand this concept with the help
of an example.
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void eat(){[Link]("eating bread...");}
}
class Cat extends Animal{
void eat(){[Link]("eating rat...");}
}
class Lion extends Animal{
void eat(){[Link]("eating meat...");}
}
class TestPolymorphism3{
public static void main(String[] args){
Animal a;
a=new Dog();
[Link]();
a=new Cat();
[Link]();
a=new Lion();
[Link]();
}}
//Dynamic Method Dispatch
class Dispatch{
class A{ public static void main(String args[]){
void callme(){ A a=new A();
[Link](“Inside A’s callme method”); B b=new B();
C c=new C();
}
} A r;
class B extends A{
void callme(){ r=a;
[Link]();
[Link](“Inside B’s callme method”);
} r=b;
} [Link]();
class C extends A{
r=c;
void callme(){
[Link]();
[Link](“Inside C’s callme method”); }
} }
}
Output:
Inside A's callme method
Inside B's callme method
Inside C's callme method
Static variables class stvar
class A {
{ public static void main(String ar[])
static String cname; {
String name; A a1=new A();
int rno; A a2=new A();
[Link]="Jaffar";
void display() [Link]=1201;
{ [Link]="SNIST";
[Link]("Student name: " + name); [Link]();
[Link]("Student rno: " + rno);
[Link]("College name: " + cname); [Link]="Sameer";
[Link]=1202;
} [Link]();
} }
}
Static variables class stvar
class A {
{ public static void main(String ar[])
static String cname; {
String name; [Link] =“SNIST”;
int rno; A a1=new A();

void display() [Link]="Jaffar";


{ [Link]=1201;
[Link]("Student name: " + name); [Link]();
[Link]("Student rno: " + rno);
[Link]("College name: " + cname); }
}
}
}
Static variables class stvar
class A {
{ public static void main(String ar[])
static String cname; {
String name; [Link] =“SNIST”;
int rno; A a1=new A();
A a2=new A();
void display() [Link]="Jaffar";
{ [Link]=1201;
[Link]("Student name: " + name); [Link]();
[Link]("Student rno: " + rno); [Link]="Sameer";
[Link]("College name: " + cname); [Link]=1202;
[Link]();
}
} }
}
class A class stvar
{ {
static String cname; public static void main(String ar[])
String name; {
int rno; A a1=new A();
A a2=new A();
void display() [Link]="Jaffar";
{ [Link]=1201;
[Link]("Student name: " + name); [Link]="SNIST";
[Link]("Student rno: " + rno); [Link]();
[Link]("College name: " + cname);
[Link](); [Link]="Sameer";
[Link]=1202;
} [Link]="CBIT";
} [Link]();
[Link]();
}
}
Static Methods:

class Smethod
{
static void display()
{
[Link]( "HI from display");
}
}

class Statictest
{
public static void main(String a[])
{
[Link]();
}
}
class Smethod
{
static int x=10;
static void display()
{
[Link]( "HI from display");
[Link]( x );
}
}

class statictest
{
public static void main(String a[])
{
[Link]();
}
}
class Smethod
{
int x=10;
static void display()
{
[Link]( "HI from display");
[Link]( x );
}
}

class statictest
{
public static void main(String a[])
{
[Link]();
}
}
Static Blocks:
class statictest
class Sblock
{
{
public static void main(String a[])
static
{
{
[Link]("Hi from static block" ); Sblock s = new Sblock();
}
}
}
Sblock()
{
[Link]("Hi from constructor" );
}

static void display()


{
[Link]( "HI from display");
}
}
Static Blocks:
class statictest
class Sblock
{
{
public static void main(String a[])
static
{
{
[Link]("Hi from static block" ); [Link]();
}
}
}
Sblock()
{
[Link]("Hi from constructor" );
}

static void display()


{
[Link]( "HI from display");
}
}
class A
{ class Abs1
static {
{ public static void main(String a[])
[Link]("HI from static from A"); {
} B ob = new B();
A() [Link]();
{ [Link]();
[Link]("HI from A constructor"); }
} }
void show()
{ [Link]("HI from show");
}
}
class B extends A
{
static
{
[Link]("HI from static from B");
}
B()
{
[Link]("HI from B constructor");
}
void display()
{ [Link]("HI from display");
}
}
Using final with Inheritance
The keyword final has three uses:
To create a constant variable
To prevent overriding
To prevent inheritance

To create a constant variable:


– A variable can be declared as final. Doing so prevents its contents from being
modified. This means that you must initialize a final variable when it is declared.

class FinalDemo{
public static void main(String sree[]){
final int i=20;
System [Link](i);
//i=i+1; can’t assign a value to final variable i
//[Link](i); cannot assign a value to final variable i
}
}
To prevent overriding
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.

class A {
final void display() {
[Link]("This is a final method.");
}
}

class B extends A {
void display() { // ERROR! Can't override.
[Link]("Illegal!");
}
}
To prevent inheritance
→To prevent a class from being inherited precede the class declaration with
final.

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

final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
➢ Normally, Java resolves calls to methods dynamically, at run time. This
is called late binding.
➢ However, since final methods cannot be overridden, a call to one can
be resolved at compile time. This is called early binding.
Abstract Classes

➢ Data abstraction is the process of hiding certain details and showing only
essential information to the user.
Abstraction can be achieved with abstract classes
Abstract class: is a restricted class that cannot be used to create objects (to
access it, it must be inherited from another class).

➢ Any class that contains one or more abstract methods must also be declared
abstract.
Abstract method: A method that has been declared but not defined is an
abstract method.
Abstract method can only be used in an abstract class, and it does not have a
body. The body is provided by the subclass (inherited from)

➢ You must declare the abstract method with the keyword abstract:
abstract type name (parameter-list);

➢ You must declare the class with the keyword abstract:


abstract class MyClass{
......
}
➢ An abstract class is incomplete class, It may contain methods with
“missing” bodies.

➢ You cannot instantiate (create a new instance of) an abstract class but you
can create reference to an abstract class.

➢ Also, you cannot declare abstract constructors, or abstract static methods.

➢ You can declare a class to be abstract even if it does not contain any
abstract methods. This prevents the class from being instantiated.

➢ An abstract class can also have concrete methods.


// A Simple demonstration of abstract.
abstract class A
{
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
[Link]("This is a concrete method.");
}
}
class B extends A {
void callme() {
[Link]("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
[Link]();
[Link]();
}
} Output:
B's implementation of callme.
This is a concrete method.
import [Link]; class Abs3
abstract class Help {
{ public static void main(String ar[])
int x,y; {
void read() B b= new B();
{ [Link]();
Scanner s=new Scanner([Link]); [Link]();
[Link]("Enter 2 values"); }
x= [Link](); }
y=[Link]();
}
abstract void area();
}

class B extends Help


{
void area()
{
int a= x*y;
[Link]("AREA : " + a);
}
}
The Object Class
➢ Object is a special class, defined by Java.

➢ Object is a superclass of all other classes.

➢ This means that a reference variable of type Object can refer to an object
of any other class.

➢ Object defines the following methods:


Method
Purpose
Object clone( ) ………… Creates a new object that is the same as the object being cloned.

boolean equals(Object object) ………….. Determines whether one object is equal to another.

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

void notifyAll( ) ………… Resumes execution of all threads waiting onthe 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 nanoseconds)
interface
• Interface is also one of the type of class it contains only
abstract methods. And Interfaces not alternative for
abstract class it is extension for abstract classes.
• The abstract class contains at least one abstract method
but the interface contains only abstract methods.
• For the interfaces the compiler will generates .class files.
• Interfaces giving the information about the functionalities
and these are not giving the information about internal
implementation.
• Inside the source file it is possible to declare any number of
interfaces. And we are declaring the interfaces by using
interface keyword.
• Syntax:-Interface interface-name interface it1 { }
Uses of Interfaces
• Uses of Interfaces in Java are mentioned below:
• It is used to achieve abstraction.
• Since java does not support multiple inheritances in the
case of class, by using an interface it can achieve
multiple inheritances.
• Any class can extend only 1 class but can any class
implement an infinite number of interface.
• It is also used to achieve loose coupling.
• Interfaces are used to implement abstraction.
• To achieve security - hide certain details and only show
the important details of an object (interface).
➢Once an interface is defined, any number of classes can implement an
interface.

➢Also, one class can implement any number of interfaces.

➢Using the keyword interface, you can fully abstract a class’ interface
from its implementation.

➢Using the keyword implements, you can implement any number of


interfaces.

➢The methods in interface are public by default.

➢The variables in interface are final and static by default.


Defining an Interface
An interface is defined much like a class. This is the general form of an interface:

access interface interfacename


{ return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Example2:
Example1:
interface Stack
interface Help { void push(int item);
{ int pop();
void read(); void display();
} }
Implementing Interfaces

Once an interface has been defined, one or more classes can implement that
interface.

To implement an interface, include the implements clause in a class definition,


and then create the methods defined by the interface.

The general form of a class that includes the implements clause looks like this:

access class classname [extends superclass] [implements interface [,interface...]]


{
// class-body
}

class MyStack implements Stack


{
}
Example program:

Import [Link].*;
interface printable{
Public Abstract void print();
}
class A6 implements printable{
public void print(){[Link]("Hello");}

public static void main(String args[]){


A6 obj = new A6();
[Link]();
}
}
➢ If a class implements more than one Interface, the interfaces are separated
with a comma.

➢ If a class implements two interfaces that declare the same method, then the
same method will be used by clients of either interface.

➢ The methods that implement an interface must be declared public.

➢ Also, the type signature of the implementing method must match exactly
the type signature specified in the interface definition.
interface SoundType{
void sound();
}

class Person implements SoundType class Cat implements SoundType class Radio implements SoundType
{ { {
public void sound() public void sound() public void sound()
{ { {
[Link]("Hello I am [Link]( [Link]( "I can sing a
human being"); "Meeeeeowwwwwwww"); song for you");
} } }
void display() } }
{ public class InterfaceEx
[Link](“Hi”);
{ public static void main(String[] args)
}
} { Person p=new Person();
Cat c=new Cat();
Radio r=new Radio();
SoundType s;
s=p;
[Link]();
[Link](); // Error
s=c;
[Link]();
s=r;
[Link]();
} }
Partial Implementations
➢ If a class includes an interface but does not fully
implement the methods defined by that interface,
then that class must be declared as abstract.

➢ When any class extends the Parent class or


implement any interface then the child class must
override all the abstract methods of Parent class
or interface. But if child class does not override all
the methods then it must be declared as abstract
class and all the child of Child class (Multilevel)
must override remaining methods.
Partial Implementations([Link].)
interface Study{
void theory( );
void practical( );
}
abstract class Room implements Study{
@Override
public void theory( ) {
[Link]("Theory Work in Class Room");
} }
class Lab extends Room{
@Override
public void practical( ) {
[Link]("Practical Work in Lab");
} }
public class PartialImplementDemo{
public static void main(String []a) {
Lab L= new Lab();
[Link]();
[Link]();
} }
Variables in Interfaces
You can define variables in an interface but implicitly they are final and static.
That is you can’t modify them.
[Link]
[Link] class FinalImpl implements InterDemo
Interface InterDemo {
{ public void show()
int i=100; { [Link]("FinalTest :Show()");
void show(); }
} }
class FinalTest
{ public static void main(String sree[])
{ [Link](“ i = “ + InterDemo.i);
FinalImpl fi=new FinalImpl();
[Link]();
//fi.i=200; can’t assign a value to variable i
[Link]("FinalDemo Varaible i :"+fi.i);
}
}

Output: i = 100
FinalTest :Show()
FinalDemo Varaible i :100
Interfaces Can Be Extended
One interface can inherit another by use of the keyword extends.

The syntax is the same as for inheriting classes.


interface A {
void m1();
void m2();
}
interface B extends A {
void m3();
}

B now includes m1() and m2() -- it adds m3().


When a class implements an interface, that inherits some other interface, then it
must provide implementations for all methods defined within the interface
inheritance chain.
// One interface can extend another. public void method2()
interface A { [Link]("Implement m2().");
{ void meth1(); }
void meth2(); public void method3()
} { [Link]("Implement m3().");
// B now includes meth1() and meth2() -- it adds meth3(). }
interface B extends A
}
{ void meth3();
class IFExtend
}
{ public static void main(String arg[])
// This class must implement all of A and B
{ MyClass ob = new MyClass();
class MyClass implements B
ob.m1();
{ public void method1()
{[Link]("Implement m1()."); ob.m2();
} ob.m3();
}
} Output:
Implement m1().
Implement m2().
Implement m3().
Understanding relationship between classes
and interfaces
Multiple inheritance in Java by interface
interface A
{
void m1();
}
interface B
{
void m2();
}

class Test implements A,B


{
void m1()
{
[Link](“m1 implementation”);
}
void m2()
{
[Link](“m2 implementation”);
}
void display()
{
[Link](“ concrete method of Test”);
}
}
The difference between Class and Interface are listed below

CLASS INTERFACE
➢The ‘class’ keyword is used to create a ➢The ‘interface’ keyword is used to create
class. an interface
➢An object of a class can be created. ➢An object of an interface cannot be
created.
➢Class doesn’t support multiple ➢Interface supports multiple inheritance.
inheritance.
➢A class can inherit another class. ➢An Interface cannot inherit a class.

➢A class can be inherited by another class ➢An Interface can be inherited by a class
using the keyword ‘extends’. using the keyword ‘implements’ and it can
be inherited by another interface using the
keyword ‘extends’.
➢A class can contain constructors. ➢An Interface cannot contain constructors.

➢It cannot contain abstract methods. ➢It consists of abstract methods only.

➢Variables and methods can be declared ➢Variables and methods are declared as
using any specifiers like public, protected, public only.
default, private.
Abstract Class Vs Interface
➢ An abstract class is written when there are some common features are shared
among the objects.
➢ An interface is written when all the features are implement differently in
different objects.

➢ When an abstract class is written, it is the duty of the programmer to provide


sub classes to it.
➢ An interface is written when the programmer wants to leave the implementation
to the third party vendors.

➢ An abstract class contains some abstract methods and also some concrete
methods.
➢ An interface contains only abstract methods.

➢ An abstract class can contain instance variables also.


➢ An interface can not contain instance variables. It contains only constants.
➢ All the abstract methods of the abstract class should be implemented in its sub
classes.
➢ All the (abstract) methods of the interface should be implemented in its
implementation classes.

➢ Abstract class is declared by using the keyword abstract.


➢ Interface is declared using the keyword interface.

➢ An abstract class can only inherit a single super class (abstract or otherwise).
➢ A class can implement more than one interface.

➢ Interfaces have no direct inherited relationship with any particular class, they are
defined independently. Interfaces themselves have inheritance relationship
among themselves.

➢ An abstract methods of abstract class have abstract modifier.


➢ A method of interface is an abstract method by default.
• Abstract classes are for
Generalization
• Interfaces are for standardization
Uses of Interface
➢ To reveal an object's programming interface (functionality of the object)
without revealing its implementation.
– This is the concept of encapsulation.
– The implementation can change without affecting the caller of the
interface.

➢ To have unrelated classes implement similar methods (behaviors).


– One class is not a sub-class of another.

➢ To model multiple inheritance.


– A class can implement multiple interfaces while it can extend only one
class.

You might also like