SlideShare a Scribd company logo
1 of 19
INTERFACE
• 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 methods and variables but the methods
declared in interface contain only method
signature, not body.
Why use Java interface?
• There are mainly three reasons to use
interface. They are given below.
• It is used to achieve abstraction.
• By interface, we can support the functionality
of multiple inheritance.
• It can be used to achieve loose coupling.
How to declare interface?
• Interface is declared by using interface keyword. It provides total
abstraction; means all the methods in interface are declared with
empty body and are public and all fields are public, static and final
by default. A class that implement interface must implement all the
methods declared in the interface.
• Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
abstract classes may contain non-final variables,
whereas variables in interface are final, public
and static.
// A simple interface
interface Player
{
final int id = 10;
int move();
}
// Java program to demonstrate working of
// interface.
import java.io.*;
// A simple interface
interface in1
{
// public, static and final
final int a = 10;
// public and abstract
void display();
}
// A class that implements interface.
class testClass implements in1
{
// Implementing the capabilities of
// interface.
public void display()
{
System.out.println("Geek");
}
// Driver Code
public static void main (String[] args)
{
testClass t = new testClass();
t.display();
System.out.println(a);
}
}
Output:
Geek 10
• This is how a class implements an interface. It
has to provide the body of all the methods
that are declared in interface or in other
words you can say that class has to implement
all the methods of interface.
interface MyInterface
{
/* compiler will treat them as:
* public abstract void method1();
* public abstract void method2();
*/
public void method1();
public void method2();
}
class Demo implements MyInterface
{
/* This class must have to implement both the abstract methods * else you will get compilation error */
public void method1()
{
System.out.println("implementation of method1");
}
public void method2()
{
System.out.println("implementation of method2");
}
public static void main(String arg[])
{
MyInterface obj = new Demo(); obj.method1();
}
}
OUTPUT
implementation of method1
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();
}
}
Extending Interface
• One interface can inherit another by use of the
keyword extends. The syntax is the same as for
inheriting classes.
• When a class implements an interface that
inherits another interface,
• It must provide implementation of all methods
defined within the interface inheritance.
• Note : Any class that implements an interface
must implement all methods defined by that
interface, including any that inherited from other
interfaces.
interface if1
{
void dispi1();
}
interface if2 extends if1
{
void dispi2();
}
class cls1 implements if2
{
public void dispi1()
{
System.out.println("This is display of i1");
}
public void dispi2()
{
System.out.println("This is display of i2");
}
}
public class Ext_iface
{
public static void main(String args[])
{
cls1 c1obj = new cls1();
c1obj.dispi1();
c1obj.dispi2();
}
}
Output :
This is display of i1
This is display of i2
Note : We have to define disp1() and disp2() in
cls1.
interface Interface1
{
public void f1();
}
//Interface2 extending Interface1
interface Interface2 extends Interface1
{
public void f2();
}
class x implements Interface2
{
//definition of method declared in interfacel
public void f1()
{
System.out.println("Contents of Method f1() in Interface1");
}
public void f2()
{
System.out.println("Contents of Method f2() in Interface2");
}
public void f3()
{
System.out.println("Contents of Method f3() of Class X");
}
}
class ExtendingInterface
{
public static void main(String[] args)
{
Interface2 v2; //Reference variable of Interface2
v2 = new x(); //assign object of class x
v2.f1();
v2.f2();
x xl=new x();
xl.f3();
}
}
Multiple inheriance using interface..
class stu
{
int rollno;
String name = new String();
int marks;
stu(int r, String n, int m)
{
rollno = r;
name = n;
marks = m;
}
}
interface i
{
void display();
}
class studerived extends stu implements i
{
studerived(int r, String n, int m)
{
super(r,n,m);
}
public void display()
{
System.out.println("Displaying student details .. ");
System.out.println("Rollno = " + rollno);
System.out.println("Name = " + name);
System.out.println("Marks = " + marks);
}
}
public class Multi_inhe_demo
{
public static void main(String args[])
{
studerived obj = new studerived(1912, "Ram", 75);
obj.display();
}
}
OBJECT CLONNING
• The object cloning is a way to create exact copy
of an object. The clone() method of Object class
is used to clone an object.
• The java.lang.Cloneable interface must be
implemented by the class whose object clone we
want to create. If we don't implement Cloneable
interface, clone() method generates
CloneNotSupportedException.
• The clone() method is defined in the Object class.
Syntax of the clone() method is as follows:
• protected Object clone() throws CloneNotSuppor
tedException
Advantage of Object cloning
• You don't need to write lengthy and repetitive
codes.
• It is the easiest and most efficient way for
copying objects, especially if we are applying it
to an already developed or an old project. Just
define a parent class, implement Cloneable in
it, provide the definition of the clone()
method and the task will be done.
• Clone() is the fastest way to copy array.
Disadvantage of Object cloning
• To use the Object.clone() method, we have to
change a lot of syntaxes to our code, like
implementing a Cloneable interface
• We have to implement cloneable interface
while it doesnot have any methods in it.
Example of clone() method (Object
cloning)
class Student18 implements Cloneable{
int rollno;
String name;
Student18(int rollno,String name){
this.rollno=rollno;
this.name=name;
}
public Object clone()throws CloneNotSupportedException{
return super.clone();
}
public static void main(String args[]){
try{
Student18 s1=new Student18(101,"amit");
Student18 s2=(Student18)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}catch(CloneNotSupportedException c){}
}
}

More Related Content

What's hot

03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: MethodsSvetlin Nakov
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classesIntro C# Book
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Nishan Barot
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptmanish kumar
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro C# Book
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)Gandhi Ravi
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritancemanish kumar
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritanceIntro C# Book
 

What's hot (20)

Java Programming - 03 java control flow
Java Programming - 03 java control flowJava Programming - 03 java control flow
Java Programming - 03 java control flow
 
Java ppt
Java pptJava ppt
Java ppt
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Java programs
Java programsJava programs
Java programs
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
 
Initial Java Core Concept
Initial Java Core ConceptInitial Java Core Concept
Initial Java Core Concept
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 

Similar to Interface

Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdfKp Sharma
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.pptrani marri
 
12.2 Abstract class and Interface.ppt
12.2 Abstract class and Interface.ppt12.2 Abstract class and Interface.ppt
12.2 Abstract class and Interface.pptVISHNUSHANKARSINGH3
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)ssuser7f90ae
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...yazad dumasia
 
Interface and abstraction
Interface and abstractionInterface and abstraction
Interface and abstractionRaghav Chhabra
 
OOFeatures_revised-2.pptx
OOFeatures_revised-2.pptxOOFeatures_revised-2.pptx
OOFeatures_revised-2.pptxssuser84e52e
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using ReflectionGanesh Samarthyam
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT studentsPartnered Health
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfacesKalai Selvi
 
U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptxmadan r
 
8abstact class in c#
8abstact class in c#8abstact class in c#
8abstact class in c#Sireesh K
 
Abstraction in Java: Abstract class and Interfaces
Abstraction in  Java: Abstract class and InterfacesAbstraction in  Java: Abstract class and Interfaces
Abstraction in Java: Abstract class and InterfacesJamsher bhanbhro
 
Java tutorials
Java tutorialsJava tutorials
Java tutorialssaryu2011
 

Similar to Interface (20)

Interface
InterfaceInterface
Interface
 
Interface
InterfaceInterface
Interface
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdf
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
 
12.2 Abstract class and Interface.ppt
12.2 Abstract class and Interface.ppt12.2 Abstract class and Interface.ppt
12.2 Abstract class and Interface.ppt
 
Inheritance
InheritanceInheritance
Inheritance
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
 
14 interface
14  interface14  interface
14 interface
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
 
Interface and abstraction
Interface and abstractionInterface and abstraction
Interface and abstraction
 
OOFeatures_revised-2.pptx
OOFeatures_revised-2.pptxOOFeatures_revised-2.pptx
OOFeatures_revised-2.pptx
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfaces
 
U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptx
 
8abstact class in c#
8abstact class in c#8abstact class in c#
8abstact class in c#
 
Abstraction in Java: Abstract class and Interfaces
Abstraction in  Java: Abstract class and InterfacesAbstraction in  Java: Abstract class and Interfaces
Abstraction in Java: Abstract class and Interfaces
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 

Recently uploaded

Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 

Recently uploaded (20)

young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 

Interface

  • 2. • 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 methods and variables but the methods declared in interface contain only method signature, not body.
  • 3. Why use Java interface? • There are mainly three reasons to use interface. They are given below. • It is used to achieve abstraction. • By interface, we can support the functionality of multiple inheritance. • It can be used to achieve loose coupling.
  • 4. How to declare interface? • Interface is declared by using interface keyword. It provides total abstraction; means all the methods in interface are declared with empty body and are public and all fields are public, static and final by default. A class that implement interface must implement all the methods declared in the interface. • Syntax: interface <interface_name> { // declare constant fields // declare methods that abstract // by default. }
  • 5. abstract classes may contain non-final variables, whereas variables in interface are final, public and static. // A simple interface interface Player { final int id = 10; int move(); }
  • 6. // Java program to demonstrate working of // interface. import java.io.*; // A simple interface interface in1 { // public, static and final final int a = 10; // public and abstract void display(); } // A class that implements interface. class testClass implements in1 { // Implementing the capabilities of // interface. public void display() { System.out.println("Geek"); } // Driver Code public static void main (String[] args) { testClass t = new testClass(); t.display(); System.out.println(a); } } Output: Geek 10
  • 7. • This is how a class implements an interface. It has to provide the body of all the methods that are declared in interface or in other words you can say that class has to implement all the methods of interface.
  • 8. interface MyInterface { /* compiler will treat them as: * public abstract void method1(); * public abstract void method2(); */ public void method1(); public void method2(); } class Demo implements MyInterface { /* This class must have to implement both the abstract methods * else you will get compilation error */ public void method1() { System.out.println("implementation of method1"); } public void method2() { System.out.println("implementation of method2"); } public static void main(String arg[]) { MyInterface obj = new Demo(); obj.method1(); } } OUTPUT implementation of method1
  • 9. 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(); } }
  • 10. Extending Interface • One interface can inherit another by use of the keyword extends. The syntax is the same as for inheriting classes. • When a class implements an interface that inherits another interface, • It must provide implementation of all methods defined within the interface inheritance. • Note : Any class that implements an interface must implement all methods defined by that interface, including any that inherited from other interfaces.
  • 11. interface if1 { void dispi1(); } interface if2 extends if1 { void dispi2(); } class cls1 implements if2 { public void dispi1() { System.out.println("This is display of i1"); } public void dispi2() { System.out.println("This is display of i2"); } } public class Ext_iface { public static void main(String args[]) { cls1 c1obj = new cls1(); c1obj.dispi1(); c1obj.dispi2(); } }
  • 12. Output : This is display of i1 This is display of i2 Note : We have to define disp1() and disp2() in cls1.
  • 13. interface Interface1 { public void f1(); } //Interface2 extending Interface1 interface Interface2 extends Interface1 { public void f2(); } class x implements Interface2 { //definition of method declared in interfacel public void f1() { System.out.println("Contents of Method f1() in Interface1"); } public void f2() { System.out.println("Contents of Method f2() in Interface2"); } public void f3() { System.out.println("Contents of Method f3() of Class X"); } } class ExtendingInterface { public static void main(String[] args) { Interface2 v2; //Reference variable of Interface2 v2 = new x(); //assign object of class x v2.f1(); v2.f2(); x xl=new x(); xl.f3(); } }
  • 14. Multiple inheriance using interface.. class stu { int rollno; String name = new String(); int marks; stu(int r, String n, int m) { rollno = r; name = n; marks = m; } } interface i { void display(); }
  • 15. class studerived extends stu implements i { studerived(int r, String n, int m) { super(r,n,m); } public void display() { System.out.println("Displaying student details .. "); System.out.println("Rollno = " + rollno); System.out.println("Name = " + name); System.out.println("Marks = " + marks); } } public class Multi_inhe_demo { public static void main(String args[]) { studerived obj = new studerived(1912, "Ram", 75); obj.display(); } }
  • 16. OBJECT CLONNING • The object cloning is a way to create exact copy of an object. The clone() method of Object class is used to clone an object. • The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException. • The clone() method is defined in the Object class. Syntax of the clone() method is as follows: • protected Object clone() throws CloneNotSuppor tedException
  • 17. Advantage of Object cloning • You don't need to write lengthy and repetitive codes. • It is the easiest and most efficient way for copying objects, especially if we are applying it to an already developed or an old project. Just define a parent class, implement Cloneable in it, provide the definition of the clone() method and the task will be done. • Clone() is the fastest way to copy array.
  • 18. Disadvantage of Object cloning • To use the Object.clone() method, we have to change a lot of syntaxes to our code, like implementing a Cloneable interface • We have to implement cloneable interface while it doesnot have any methods in it.
  • 19. Example of clone() method (Object cloning) class Student18 implements Cloneable{ int rollno; String name; Student18(int rollno,String name){ this.rollno=rollno; this.name=name; } public Object clone()throws CloneNotSupportedException{ return super.clone(); } public static void main(String args[]){ try{ Student18 s1=new Student18(101,"amit"); Student18 s2=(Student18)s1.clone(); System.out.println(s1.rollno+" "+s1.name); System.out.println(s2.rollno+" "+s2.name); }catch(CloneNotSupportedException c){} } }