0% found this document useful (0 votes)
2 views

Interface

Uploaded by

Praveen Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Interface

Uploaded by

Praveen Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Interface

Interface

• Java does not support multiple inheritance.


 Classes in java cannot have more than one base class.
 Java gives an alternate method known as interfaces to
implement the concept of multiple inheritance
Defining interfaces

 An interface is defined much like a class.


 Interfaces can have only abstract functions and final
members
 It won’t be instantiated/implemented or extended
Syntax:
accessspecifier 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;
}
Example

/* File name : Animal.java

*/ interface Animal

public void eat();

public void travel();


}
Implementing an Interface
 Once an interface has been defined, one or more
classes can implement that interface.
 To implement an interface, the ‘implements’ clause
is included in a class definition and then the methods
defined by the interface are created.
Syntax:

class classname implements interfacename


{
body of class
}
classclassname extends superclass implements interface1,interface2…
{
body of class
}
Properties of java interface
 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.
 The type signature of the implementing method must match
exactly the type signature specified in the interface
definition.
Rules
 A class can implement more than one interface at a
time.
 A class can extend only one class, but can implement
many interfaces.
 An interface can extend another interface, in a similar
way as a class can extend
• another class
Example

interface
{ Sample

final String name = “Shree”;

} void display();

{ public class testClass implements Sample // A class that implements interface.


public void display()
{
System.out.println(“Welcome”);
}
public static void main (String[] args)
{
testClass t = new testClass();
t.display();

} System.out.println(name);
}
Output:
Welcome
Shree
Example2

interface Drawable
{
void draw();
}
class Rectangle implements Drawable
{
public void draw()
{
System.out.println(“Drawing rectangle”);
}

}
Contd…
class Circle implements Drawable
{
public void draw()
{
System.out.println(“Drawing circle”);
}
}
public class TestInterface
{
public static void main(String args[])
{

Drawable d=new Circle(); d.draw();


}
}
Output:
Drawing circle
Nested Interface

 An interface can be declared as a member of a class or


another interface.
 Such an interface is called a member interface or a
nested interface.
 A nested interface can be declared as public, private,
or protected
Example

interface MyInterfaceA
{

void display();

interface MyInterfaceB
{
void myMethod();
}

}
Contd..

{
public void myMethod()
{
System.out.println(“Nested interface method”);
}
public static void main(String args[])
{

MyInterfaceA.MyInterfaceB obj= new NestedInterfaceDemo1();


obj.myMethod();
}
}
Output:
Nested interface method
Aspect for comparison Class Interface

A class is instantiated to create An interface can never be instanti- ated as the methods are
unable to perform any action on invoking.
Basic objects.

Keyword class Interface


Access The members of a class can be private, public or protected. The members of an interface are always public.
specifier
Methods The methods of a class are defined to perform a specific The methods in an interface are purely abstract.
action.

A class can implement any num- ber of interfaces and can An interface can extend multiple interfaces but cannot
extend only one class. implement any interface.
inheritance
Inheritance keyword extends implements

A class can have constructors to An interface can never have a constructor as there is
hardly any variable to initialize.
Constructor initialize the variables.

class class_Name Interface interface_Name


{ {
//fields Type var_name=value;
Declaration Syntax //Methods Type method1(parameter-list); Type
} method2(parameter-list);
..
}
OBJECT CLONING
• Object cloning refers to creation of exact copy of an object.
• It creates a new instance of the class of current object and
initializes all its fields with exactly the contents of the
corresponding fields of this object.
• In Java, there is no operator to create copy of an object.
• If we use assignment operator then it will create a copy of
reference variable and not the object.
import java.io.*;

class sample
{

int a; float b;

sample()
{
a = 10;
b = 20;
}
}
class Mainclass
{
public static void main(String[] args)
{

sample ob1 = new sample();


System.out.println(ob1.a + “ “ + ob1.b);

sample ob2 = ob1;

ob2.a = 100;

System.out.println(ob1.a+” “+ob1.b);

System.out.println(ob2.a+” “+ob2.b);
}
}
Output:
10 20.0
100 20.0
100 20.0
Creating a copy using clone() method
• 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.

Syntax
protected Object clone() throws CloneNotSupportedExc
eption
Advantage of Object cloning

• 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
• Clone() is the fastest way to copy array
class Student implements Cloneable
{
int rollno;
String name;
Student(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{
Student s1=new Student18(101,"amit");

Student s2=(Student18)s1.clone();

System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);

}catch(CloneNotSupportedException c){}

}
}
Output:
101 amit
Types of Object cloning

Types of Object cloning


• Deep Copy
• Shallow Copy
Shallow Copy:
• It is the default in cloning.
• In this method the fields of an old object ob1 are copied to the new
object ob2.
Contd..
Deep Copy
 A deep copy copies all fields, and makes copies of
dynamically allocated memory pointed to by the fields.

 A deep copy occurs when an object is copied along with the


objects to which it refers.
INNER CLASSES

• Inner classes are the nested classes.


• We can simply represent that are defined inside the other classes.
syntax :
Access_modifier class outerClass
{
//code
Access_modifier class InnerClass
{
//code
}
}
Properties of Inner class:

1.The outer class can take over as many number of inner class objects as it needs.

2.If the outer class and the equivalent inner class both are public then any new class
can create an instance of this inner class.

3.The inner class objects do not get instantiated with outer class object

4.outer class can be able to call the private functions of inner class.

5.Inner class code has open way to all members of the outer class object that
contains it.

6.If the inner class has a variable with same name then the variable of outer class’s
can be accessed in given syntax
Outerclassname.this.variable_name
Types of Nested classes

• There are two types of nested classes in java.


• non-static and static nested classes.
•The non-static nested classes are also known as inner classes.
 Non-static nested class (inner class)

○ Member inner class


○ Method Local inner class
○ Anonymous inner class
 Static nested class
Type Description

Member Inner Class A class created within class and outside method.

Anonymous Inner Class A class created for implementing interface or extending


class.
Its name is decided by the java compiler.

Method Local Inner A class created within method.


Class

Static Nested Class A static class created within class.

Nested Interface An interface created within class or interface.


Example
class Outer_class
{
int n=20;
private class Inner_class {
public void display()
{
System.out.println(“This is an inner class”);
System.out.println(“n:”+n);
}
}
void print_inner()
{
Inner_class inn = new Inner_class();
inn.display();
}
}
Contd..
public class Myclass
{
public static void main(String args[]) {
Outer_class out= new Outer_class();
out.print_inner();
}
}
Output:
This is an inner class
ARRAY LIST CLASS

 Java ArrayList class uses a dynamic array for storing the elements.

 It is like an array, but there is no size limit.

 We can add or remove elements anytime.

 It inherits the AbstractList class and implements List


interface.
Features

 Java ArrayList class can hold duplicate elements.

 Java ArrayList class maintains insertion order.

 Java ArrayList class is non-synchronized.

 Java ArrayList allows random access since array works at the index
basis.
 In Java ArrayList class, operation is slow because a lot of shifting
wants to be occurred if any element is deleted from the array list.
ArrayList class hierarchy
ArrayList class declaration
• public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable,
Serializable
Constructors of Java ArrayList

Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection It is used to build an array list that is initialized


c) with the
elements of the collection c.

ArrayList(int It is used to build an array list that has the


capacity) specified initial capacity.
Methods of Java ArrayList
Method Description
void add(int index, Object It is used to insert the specified element at the specified
element) position index in a list.
boolean addAll It is used to append all of the elements in the specified
(Collection c) collection to the end of this list, in the order that they are
returned by the specified collection’s iterator.
void clear() It is used to remove all of the elements from this list.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence
of the specified element, or -1 if the list does not contain this
element.

Object[] toArray() It is used to return an array containing all of the elements in


this list in the correct order.
Object[] toArray It is used to return an array containing all of the elements in
import java.util.*;
class Arraylist_example
{
public static void main(String args[])
{
ArrayList<String> a1=new ArrayList<String>();
a1.add(“Bala”);
a1.add(“Mala”);
a1.add(“Vijay”);
ArrayList<String> a2=new ArrayList<String>();
a2.add(“kala”);
a2.add(“Banu”);

a1.addAll(a2);
Iterator itr=a1.iterator(); while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
STRINGS

 In general string is a sequence of characters.


 String is an object that represents a sequence of
characters.
 The java.lang.String class is used to create string
object.
 In java, string is basically an object that represents
sequence of char values.
 An array of characters works same as java string.
Example : character array

char chararray[]=new char[4];

chararray[0]=’J’;

chararray[1]=’a’;

chararray[2]=’v’;
chararray[3]=’a’;
Methods
 compare()
 concat()
 equals()
 split()
 length()
 replace()
 compareTo()
 intern()
• substring() etc.
 The java.lang.String class implements Serializable,
Comparable and CharSequence interfaces.
 CharSequence interface
 used to represent sequence of characters.
 implemented by String, StringBuffer and StringBuilder classes.
 it can create string in java by using these 3 classes.
• The string objects can be created using two ways.
1. By String literal

2. By new Keyword

1.String Literal
• Java String literal is created by using double quotes.
• Example:
• String s=”welcome”;

• the JVM checks the string constant pool first.

• If the string already exists in the pool, a reference to the pooled instance is
returned
Contd..
2.By new keyword

• String s=new String(“Welcome”);


• JVM will create a new string object in normal (non pool) heap memory
and the literal “Welcome” will be placed in the string constant pool.
 The variables will refer to the object in heap (non pool).
 The java String is immutable
 cannot be changed.
 Whenever we change any string, a new instance is created.
 For mutable string, you can use StringBuffer and StringBuilder classes.
Example
public class String_Example
{

public static void main(String args[])

String s1=”java”;

char c[]={‘s’,’t’,’r’,’i’,’n’,’g’};

String s2=new String(c);

String s3=new String(“example”);

System.out.println(s1);

System.out.println(s2);

System.out.println(s3);
}
}
Java String class methods
Method Description
char charAt(int index) returns char value for the particular
index
int length() returns string length
static String format(String
format, Object... args) returns formatted string
static String format(Locale l,
String format, Object... args) returns formatted string with given
locale
String substring(int beginIndex) returns substring for given begin index

String substring(int beginIndex, returns substring for given begin index


and end index
int endIndex)
boolean contains(CharSequence s) returns true or false after matching the
sequence of char value
static String join(CharSequence delim- iter,
CharSequence... elements) returns a joined string
boolean equals(Object another) checks the equality of string with object
boolean isEmpty() checks if string is empty
String concat(String str) concatinates specified string
String replace(char old, char new) replaces all occurrences of specified char
value
String replace(CharSequence old, Char- Sequence
new) replaces all occurrences of specified CharSe-
quence
static String equalsIgnoreCase(String another)
compares another string. It doesn’t check
case.
String[] split(String regex) returns splitted string matching regex
String[] split(String regex, int limit) returns splitted string matching regex and
limit
String intern() returns interned string
int indexOf(int ch) returns specified char value index
returns specified char value index starting with given index
int indexOf(int ch, int fromIndex)
int indexOf(String substring) returns specified substring index
int indexOf(String substring, int fro- mIndex) returns specified substring index starting with given index

String toLowerCase() returns string in lowercase.


String toLowerCase(Locale l) returns string in lowercase using specified
locale.
Example
class string_method{

public static void main(String args[]){ String


s=”Java”;
s=s.concat(“ Programming”); System.out.println(s);
}
}
Output:
Java Programming

You might also like