Вы находитесь на странице: 1из 58

Abstract class in Java

• A class that is declared with abstract keyword, is known as abstract


class in java. It can have abstract and non-abstract methods (method
with body).

• Before learning java abstract class, let's understand the abstraction in


java first.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 1


Abstraction in Java
• Abstraction is a process of hiding the implementation details and
showing only functionality to the user.

• Another way, it shows only important things to the user and hides the
internal details for example sending sms, you just type the text and
send the message. You don't know the internal processing about the
message delivery.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 2


Ways to achieve Abstraction
• There are two ways to achieve abstraction in java
• Abstract class (0 to 100%)
• Interface (100%)

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 3


2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 4
Example
abstract class Shape{ class TestAbstraction1{
abstract void draw(); public static void main(String args[]){
} Shape s=new Circle1();
s.draw();
class Rectangle extends Shape{ }
void draw(){System.out.println("drawing rectangle"
);}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
}

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 5


Interface in Java
• An interface in java is a blueprint of a class. It has static, constants
and abstract methods.

• The interface in java is a mechanism to achieve abstraction. There


can be only abstract methods in the java interface not method body.
It is used to achieve abstraction and multiple inheritance in Java.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 6


Cont…
• Java Interface also represents IS-A relationship.
• It cannot be instantiated just like abstract class.
• Since Java 8, we can have default and static methods in an interface.
• Since Java 9, we can have private methods in an interface.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 7


Why use Java interface?

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 8


Internal addition by compiler

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 9


Understanding relationship between classes
and interfaces

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 10


Example
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();
}
}

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 11


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

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 12


Example
class Demo {
interface UserLogin {
public String LOGIN_MESSAGE = "Please login";
public String LOGOUT_MESSAGE = "You have been logged public static void main(String arg[]) {
out successfully.";
public String login();
public String logout(); UserLoginImpl user = new
UserLoginImpl();
}
class UserLoginImpl implements UserLogin {
System.out.println(user.login());
System.out.println(user.logout());
public String login() { }
return LOGIN_MESSAGE; }
}
public String logout() {
return LOGOUT_MESSAGE;
}
}

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 13


Java 8 Default Method in Interface

interface Drawable{ class TestInterfaceDefault{


void draw();
public static void main(String args
default void msg(){
[]){
System.out.println("default method");}
} Drawable d=new Rectangle();
class Rectangle implements Drawable{ d.draw();
public void draw(){ d.msg();
System.out.println("drawing rectangle");}
}}
}

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 14


Java 8 Static Method in Interface

interface Drawable{ class TestInterfaceStatic{


void draw(); public static void main(String args[]){
static int cube(int x){ Drawable d=new Rectangle();
return x*x*x;} d.draw();
} System.out.println(Drawable.cube(3));
class Rectangle implements Drawable{ }}
public void draw(){
System.out.println("drawing rectangle");}
}

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 15


Difference between abstract class and interface
Abstract class Interface

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

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

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

4) Abstract class can provide the implementation of Interface can't provide the implementation of
interface. abstract class.

5) The abstract keyword is used to declare abstract The interface keyword is used to declare interface.
class.

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

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 16


Example of abstract class and interface in Java
//Creating interface that has 4 methods class M extends B{
interface A{ public void a(){System.out.println("I am a");}
void a();//by default, public and abstract public void b(){System.out.println("I am b");}
void b(); public void d(){System.out.println("I am d");}
void c(); }
void d(); //Creating a test class that calls the methods of A interface
} class Test5{
abstract class B implements A{ public static void main(String args[]){
public void c(){ A a=new M();
System.out.println("I am C");} a.a();
} a.b();
a.c();
a.d();
}}

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 17


Tight Coupling
class Trip {
private Car car;
class Car {
public Trip() {
public void start() {
car = new Car(); // Tight coupling System.out.println("Car is moving now..");
} }
}
public void startTrip() {
car.start();
}
}

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 18


Loose Coupling
interface Vehicle {
public void start(); } class Trip {
class Car implements Vehicle { private Vehicle v;
public void start() { public void setVehicle(Vehicle v) {
System.out.println("Starting my trip from this.v = v;
car."); }
} }
class Bike implements Vehicle { public void startTrip() {
public void start() { this.v.start();
System.out.println("Starting my trip from }
bike."); }
} }

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 19


Cont…
class Demo {

public static void main(String arg[]) {

Trip t = new Trip();

t.setVehicle(new Car());
t.startTrip();

t.setVehicle(new Bike());
t.startTrip();
}
}

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 20


Java String

• In java, string is basically an object that represents sequence of char


values. An array of characters works same as java string. For example:
• char[] ch={'j','a','v','a','t','p','o','i','n','t'};
• String s=new String(ch);
• is same as:
• String s="javatpoint";
• Java String class provides a lot of methods to perform operations on
string such as compare(), concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 21


CharSequence Interface

• The CharSequence interface is used to represent sequence of


characters. It is implemented by String, StringBuffer and StringBuilder
classes. It means, we can create string in java by using these 3 classes.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 22


How to create String object?

• By string literal
• By new keyword

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 23


String Literal

• Java String literal is created by using double quotes. For Example:


• String s="welcome";
• Each time you create a string literal, the JVM checks the string
constant pool first. If the string already exists in the pool, a reference
to the pooled instance is returned. If string doesn't exist in the pool, a
new string instance is created and placed in the pool. For example:
• String s1="Welcome";
• String s2="Welcome";//will not create new instance

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 24


In the above example only one object will be created. Firstly JVM will not find any string object with the value
"Welcome" in string constant pool, so it will create a new object. After that it will find the string with the value
"Welcome" in the pool, it will not create new object but will return the reference to the same instance.
2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 25
By new keyword

• String s=new String("Welcome");//creates two objects and one refere


nce variable
• In such case, 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 variable s will refer to the object in heap(non
pool).

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 26


Immutable String in Java

• In java, string objects are immutable. Immutable simply means unmodifiable or


unchangeable.
• Once string object is created its data or state can't be changed but a new string
object is created.
• Let's try to understand the immutability concept by the example given below:
class Testimmutablestring{
public static void main(String args[]){
String s=“Shahid";
s.concat(“Afridi");//concat() method appends the string at the end
System.out.println(s);//will print Shahid because strings are immutable objects
}
}
2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 27
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 28


Java String compare

• By equals() method
• By = = operator
• By compareTo() method

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 29


Substring in Java

• You can get substring from the given string object by one of the two
methods:
• public String substring(int startIndex): This method returns new String
object containing the substring of the given string from specified startIndex
(inclusive).
• public String substring(int startIndex, int endIndex): This method returns
new String object containing the substring of the given string from
specified startIndex to endIndex.
• In case of string:
• startIndex: inclusive
• endIndex: exclusive

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 30


indexOf( ) &lastIndexOf( )

• Allow you to find the first and last position of a character or substring
within a string:
• indexOf(char ch) // first position of 'ch'
• indexOf(String str) // first position of 'str'
• lastIndexOf(char ch) // last position of 'ch'
• lastIndexOf(String str) // last position of 'str‘
• All the methods return -1 if the character or string is not found

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 31


startsWith( ) & endsWith( )

• Simple tests for the beginning and ending of strings can be done by
using:
• public boolean startsWith(String prefix);
• public boolean endsWith(String suffix).
• these methods return true if a comparison is done with an empty
string:
myStr.endsWith(""); // true
myStr.startsWith(""); // true

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 32


Java StringBuffer class

• Java StringBuffer class is used to create mutable (modifiable) string.


The StringBuffer class in java is same as String class except it is
mutable i.e. it can be changed.
Constructor Description

StringBuffer() creates an empty string buffer with the


initial capacity of 16.
StringBuffer(String str) creates a string buffer with the specified
string.
StringBuffer(int capacity) creates an empty string buffer with the
specified capacity as length.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 33


Example
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 34


Collections in Java
• The Collection in Java is a framework that provides an architecture to
store and manipulate the group of objects.

• Java Collections can achieve all the operations that you perform on a
data such as searching, sorting, insertion, manipulation, and deletion.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 35


What is Collection in Java

• A Collection represents a single unit of objects, i.e., a group.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 36


What is a framework in Java

• It provides readymade architecture.


• It represents a set of classes and interfaces.
• It is optional.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 37


What is Collection framework

• The Collection framework represents a unified architecture for storing


and manipulating a group of objects. It has:
• Interfaces and its implementations, i.e., classes
• Algorithm

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 38


2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 39
Methods of Collection interface
No. Method Description

1 public boolean add(E e) It is used to insert an element in this collection.

2 public boolean addAll(Collection<? extends E> c) It is used to insert the specified collection elements
in the invoking collection.

3 public boolean remove(Object element) It is used to delete an element from the collection.

4 public boolean removeAll(Collection<?> c) It is used to delete all the elements of the specified
collection from the invoking collection.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 40


Iterator interface
• Iterator interface provides the facility of iterating the elements in a
forward direction only.
No Method Description
.

1 public boolean hasNext() It returns true if the iterator has more elements
otherwise it returns false.
2 public Object next() It returns the element and moves the cursor pointer to
the next element.
3 public void remove() It removes the last elements returned by the iterator. It
is less used.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 41


List Interface
• List interface is the child List <data-type> list1= new ArrayList();
interface of Collection interface. List <data-
It can have duplicate values. type> list2 = new LinkedList();
• List interface is implemented by List <data-type> list3 = new Vector();
the classes ArrayList, LinkedList, List <data-type> list4 = new Stack();
Vector, and Stack.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 42


Array List
The ArrayList class implements the List interface. It uses a dynamic
array to store the duplicate element of different data types.

The ArrayList class maintains the insertion order and non-synchronized.


The elements stored in the ArrayList class can be randomly accessed.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 43


Example
ArrayList<String> list=new ArrayList<String>(); //Creating arraylist
list.add("Ravi"); //Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 44


LinkedList
• LinkedList implements the Collection interface. It uses a doubly linked
list internally to store the elements.
• It can store the duplicate elements. It maintains the insertion order
and is not synchronized.
• In LinkedList, the manipulation is fast because no shifting is required.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 45


Example
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 46


Vector
• Vector uses a dynamic array to store the data elements. It is similar to
ArrayList. However, It is synchronized and contains many methods
that are not the part of Collection framework.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 47


Example
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 48


Difference between Vector and ArrayList
• Vector is synchronized, which means only one thread at a time can
access the code, while arrayList is not synchronized

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 49


Cont…
• Performance: ArrayList is faster, since it is non-synchronized, while
vector operations give slower performance since they are synchronize

• Data Growth: ArrayList increments 50% of the current array size if the
number of elements exceeds its capacity, while vector increments
100% (thread-safe)

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 50


Stack
The stack is the subclass of Vector. It implements the last-in-first-out
data structure, i.e., Stack.
The stack contains all of the methods of Vector class and also provides
its methods like boolean push(), boolean peek(), boolean push(object
o), which defines its properties.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 51


Set Interface
Set Interface in Java is present in java.util package. It extends the
Collection interface.
It represents the unordered set of elements which doesn't allow us to
store the duplicate items.
We can store at most one null value in Set. Set is implemented by
HashSet, LinkedHashSet, and TreeSet.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 52


HashSet
• HashSet class implements Set Interface. It represents the collection
that uses a hash table for storage. Hashing is used to store the
elements in the HashSet. It contains unique items.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 53


Example
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 54


Example
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 55


LinkedHashSet

• LinkedHashSet class represents the LinkedList implementation of Set


Interface.
• It extends the HashSet class and implements Set interface. Like
HashSet, It also contains unique elements. It maintains the insertion
order and permits null elements.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 56


Example
LinkedHashSet<String> set=new LinkedHashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 57


TreeSet

Java TreeSet class implements the Set interface that uses a tree for
storage. Like HashSet, TreeSet also contains unique elements.

However, the access and retrieval time of TreeSet is quite fast. The
elements in TreeSet stored in ascending order.

2020 ،‫ مارچ‬06 ،‫جمعه‬ Smart Application Development 58

Вам также может понравиться