Lecture Slide - Week 6
Lecture Slide - Week 6
PROGRAMMING
USING JAVA
OUTLINE Nested Classes and
Anonymous Classes
Nested Classes in java
▪ In Java, it is possible to define a class within another class, such
classes are known as nested classes. They enable you to logically
group classes that are only used in one place, thus this increases
the use of encapsulation, and creates more readable and
maintainable code.
▪ A nested class has access to the members, including private
members, of the class in which it is nested. However, the reverse is
not true i.e., the enclosing class does not have access to the
members of the nested class.
▪ A nested class is also a member of its enclosing class.
▪ As a member of its enclosing class, a nested class can be declared
private, public, protected, or package private(default).
Why Use Nested Classes?
• Logical grouping of classes—If a class is useful to only one other
class, then it is logical to embed it in that class and keep the two
together.
class OuterClass
{
...
class NestedClass
{
...
}
}
Static Nested Classes
• A static nested class is associated with its outer class similar to class
methods and variables.
• Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass
• For example, to create an object for the static nested class, use this
syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
// a static nested class
// outer class
public class StaticNestedClassDemo
class OuterClass {
{ public static void main(String[] args)
{
static int outer_x = 10; OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
int outer_y = 20;
private static int outer_private = 30; nestedObject.display();
static class StaticNestedClass }
{ }
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);
}
}
}
Inner Classes(Non-static nested classes)
• An inner class is associated with an instance of its enclosing class
and has direct access to that object's methods and fields.
• To instantiate an inner class, we must first instantiate the outer class. Then,
create the inner object within the outer object.
• Syntax:
OuterClass.InnerClass innerObject =
outerObject.new InnerClass();
}
}
}
Example 2
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
void display(){
Inner in=new Inner();
in.msg();
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
obj.display();
}
}
Local Inner Classes
• Local classes are classes that are defined in a block, which is a group of
zero or more statements between balanced braces.
For example, we can define a local class in a method body, a for loop, or an
if clause.
• A local class has access to the members of its enclosing class.
• The scope of local inner class is restricted to the block they are defined in.
• Local inner class cannot be instantiated from outside the block where it is
created in.
• Till JDK 7,Local inner class can access only final local variable of the
enclosing block. However From JDK 8, it is possible to access the non-final
local variable of enclosing block in local inner class.
More points of Local Inner Class
• A local class has access to the members of its enclosing class.
• Local inner classes can extend an abstract class or can also
implement an interface.
• Local inner could be abstract in nature also
• Local inner classes cannot be provided any access modifier
like: private, public or protected
What happens at compile time?
When a program containing a local inner class is compiled, the compiler generate
two .class files, one for the outer class and the other for the inner class that has
the reference to the outer class. The two files are named by compiler as:
Outer.class
Outer$1Inner.class
Example of Local class(Defined inside method)
class abc public class Main
{
{
int a=12,b=34;
void calculate() public static void main(String[] args)
{ {
class def
abc ob = new abc();
{
int sumCalculate() ob.calculate();
{ }
return (a+b);
}
}
int mulCalculate()
{
return (a*b);
}
}
def ob=new def();
System.out.println("Sum is "+ ob.sumCalculate());
System.out.println("Mul is "+ ob.mulCalculate());
}
}
The inner class cannot be declared as static. Inner classes are associated with the block
they are defined within and not with the external class(Outer in this case).
Java code to demonstrate the scope of inner class
public class Outer
{ private void myMethod()
{
class Inner
{
private void innerMethod()
{
System.out.println("Inside inner class");
}
}
}
public static void main(String[] args)
{
Outer outer = new Outer();
Inner inner = new Inner();
inner.innerMethod();
}
}
The above program causes compilation error because the scope of inner classes are restricted to the block they
are defined in.
Anonymous Classes
• Anonymous classes enable us to declare and instantiate a class
at the same time.
• They are like local classes except that they do not have a
name.
• The anonymous class expression consists of the following:
1. The new operator
2. The name of an interface to implement or a class to extend.
3. Parentheses that contain the arguments to a constructor, just like
a normal class instance creation expression.
4. A body, which is a class declaration body. More specifically, in
the body, method declarations are allowed but statements are not.
➢ Anonymous classes have the same access to local variables of the enclosing
scope as local classes:
• An anonymous class has access to the members of its enclosing class.
➢ Anonymous classes also have the same restrictions as local classes with
respect to their members:
• We cannot declare static initializers or member interfaces in an anonymous class.
• An anonymous class can have static members provided that they are constant
variables.
Outerclass.class
Outerclass$Nestedclass.class
class Main
{
public static void main(String[] args)
{
A ob = new A() // annoymous inner class
{
void show()
{
System.out.println("Overridden " +x);
}
};
ob.show();
}
}
2. Anonymous Inner class that implements an interface
We can also have an anonymous inner class that implements an interface
interface A
{
int x=12;
void show();
}
class Main
{
public static void main(String[] args)
{
A ob = new A() // annoymous inner class
{
public void show()
{
System.out.println("Overridden " +x);
}
};
ob.show();
}
}
3. Anonymous class that extends abstract class
abstract class Example
{
abstract void display();
}
class Main
{
public static void main(String[] args)
{
Example ref = new Example() // annoymous inner class
{
void display(){ System.out.print("Hello"); }
};
ref.display();
}
}
Comparison between normal or regular class and static nested class
S.NO Normal/Regular inner class Static nested class
Color
Package Containing classes
Graphics
Font
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to
• NOTE: If no package is specified, the classes in the file
package");
goes into a special unnamed package (the same unnamed
} package for all files).
}
HOW DOESTHE JAVA RUN-TIME SYSTEM KNOWWHERETO
LOOK FOR PACKAGESTHATYOU CREATE?
First, by default, the Java run-time system uses the current working
directory as its starting point. Thus, if your package is in a subdirectory of
the current directory, it will be found.
Second, you can specify a directory path or paths by setting the
CLASSPATH environmental variable.
Third, you can use the-classpath option with java and javac to specify the
path to your classes.
PREDICT THE OUTPUT?
PREDICT THE OUTPUT?
Note:Only one package is valid in java,more than one package in a single source code invalid in
java
NAMING CONVENTIONS
• Note: If you import a package, all the classes and interface of that
package will be imported excluding the classes and interfaces of the
subpackages. Hence, you need to import the subpackage as well.
PREDICT THE OUTPUT?
PREDICT THE OUTPUT?
HOW TO ACCESS PACKAGE FROM ANOTHER PACKAGE?
There are three ways to access the package from outside the package.
1. import java.util.Scanner;
2. import java.util. Scanner.*;
3. import java.util.*;
4. import java.util;
WHICH IS CORRECT?
1. If you use package.* then all the classes and interfaces of this
package will be accessible but not sub-packages.
2. The import keyword is used to make the classes and interface of
another package accessible to the current package.
//save byA.java EXAMPLE
package pack;
public class A{
public void msg()
{System.out.println("Hello");}
Output:
} HELLO
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
USING PACKAGENAME.CLASSNAME
If you import package.classname then only declared class of this package will be accessible.
//save byA.java
package pack;
public classA{
public void msg(){System.out.println("Hello");
}
}
Output:Hello
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = newA();
obj.msg();
}
}
USING FULLY QUALIFIED NAME
• If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.
• It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
//save by A.java EXAMPLE:
package pack;
public class A{
public void msg(){System.out.println("Hello");}
Output:Hello
}
//save by B.java package mypack; class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name obj.msg();
}
}
EXAMPLE:
class test
{
Public static void main(string[] args)
Note:
{
• Problem with readability
Java.util.Arraylist l=new • Increase length code
java.util.ArrayList();
• Solve this problem using import statement. It is no
} required to use fully qualified name we can use short name
directly.
}
EXAMPLE:
EXAMPLE:
MULTIPLE PACKAGE SCENARIO:
• In that scenario:
• Highest priority will go to explicit class import
• Next level will goes to classes present in current working directory (default
package)
• Implicit class import
EXAMPLE:
1. Import java.*;
2. Import java.util.*;
3. Import java.util.regex.*;
4. No import required
WHICH ONE ISVALID?? (IMPORTINGA PACKAGETO USE PATTERN
CLASS IN PROGRAM)
1. Import java.*;
2. Import java.util.*;
3. Import java.util.regex.*;
4. No import required
DEFAULT:PACKAGESAVAILABLE IN JAVA
class example
{
public static void main (String[] Args)
String s= new String(“main”);
}
}
STATIC IMPORT
• According to sun: usage of static import reduces code improves readability
• But according to www expert (like us): usage of static import creates
confusion and reduces readability
• Hence if there is not specific requirement it is not recommended to use
static import.
• for static import:
• Explicit (import static packagename.classname.staticmember
example import static java.lang.math.sqrt;
• Implicit (import static package name .classname.*)
example:import static java.lang.math.*;
EXAMPLE
Without static import With static import
EXAMPLE
With static import
EXAMPLE
• import java.lang.Math.*;
• import static java.lang.Math.*;
• import java.lang.Math.sqrt*;
• import static java.lang.Math.sqrt();
• import java.lang.Math.sqrt;
• import static java.lang.Math.*;
• import java.lang;
• import static java.lang;
• import java.lang.*;
• import static java.lang.*;
WHICH PACKAGE IS VALID?
• If a class declared as the final then we can't creates the child class that is
Class
inheritance concept is not applicable for final classes.
• If a variable declared as the final then we need to look for the type of variables
Variables
and then correspondingly actions need to be taken (discussed later in the slides).
EXAMPLE
final class Test
{
void methodOne( )
{
System.out.println(“Protected Member Access
Modifier”);
}
}
class public static void main(String args[])
Test1 {
extends Test t=newTest();
Every method present inside a final class is always final Test t.methodOne();
{ Test1 b = newTest1();
by default whether we are declaring or not. But every b.methodOne();
variable present inside a final class need not be final. Test c = newTest1();
c.methodOne();
}
}
FINAL VARIABLES IN INSTANCE VARIABLES
• If the value of a variable is varied from object to object such type of variables are
called instance variables.
• For every object a separate copy of instance variables will be created.
• For the instance variables it is not required to perform initialization explicitly jvm will
always provide default values.
FINAL VARIABLES IN INSTANCE VARIABLES
• For the final instance variables we should perform initialization before constructor
completion. That is the following are various possible places for this.
• Initialization while declaration, instance initialization block, and constructor.
FINAL VARIABLES IN STATIC VARIABLES
• If the static variable declare as final then compulsory we should perform initialization
explicitly whether we are using or not otherwise we will get compile time error.(The
JVM won't provide any default values)
• For the final static variables we should perform initialization before class loading
completion otherwise we will get compile time error. That is the following are
possible places.
• Initialization while declaration and inside static block.
FINAL VARIABLES IN LOCAL VARIABLES
77
Java 2 Collections
• A collection is an object that groups multiple
elements into a single unit
• Very useful
» store, retrieve and manipulate data
» transmit data from one method to another
» data structures and methods written by hotshots in the field
• Joshua Bloch, who also wrote the Collections tutorial
Collections Framework
• Unified architecture for representing and manipulating collections.
• A collections framework contains three things
» Interfaces
» Implementations
» Algorithms
79
Collections Framework Diagram
80
Collection Interface
• Defines fundamental methods
» int size();
» boolean isEmpty();
» boolean contains(Object element);
» boolean add(Object element); // Optional
» boolean remove(Object element); // Optional
» Iterator iterator();
81
Example - SimpleCollection
public class SimpleCollection {
public static void main(String[] args) {
Collection c;
c = new ArrayList();
System.out.println(c.getClass().getName());
for (int i=1; i <= 10; i++) {
c.add(i + " * " + i + " = "+i*i);
}
Iterator iter = c.iterator();
while (iter.hasNext())
System.out.println(iter.next());
}
}
82
List Interface Context
Collection
List
83
List Interface
• The List interface adds the notion of order to a collection
• The user of a list has control over where an element is added in the
collection
• Lists typically allow duplicate elements
• Provides a ListIterator to step through the elements in the list.
84
ListIterator Interface
• Extends the Iterator interface
• Defines three fundamental methods
» void add(Object o) - before current position
» boolean hasPrevious()
» Object previous()
85
ArrayList and LinkedList Context
Collection
List
ArrayList LinkedList
86
List Implementations
• ArrayList
» low cost random access
» high cost insert and delete
» array that resizes if need be
• LinkedList
» sequential access
» low cost insert and delete
» high cost random access
87
ArrayList
1. An ArrayList is one of the resizable list implementaions of the generic list interface, the other being
Vector Class.
2. Each ArrayList object has a capacity. The capacity is the size of the array used to store the elements
in the list and it is as large as the list size. As the elements are added into the list, its capacity grows
automatically.
3. The ArrayList concept provides the facility by creating an array of some default size. If it becomes
insufficient to add more elements into this initial array then system creates a new larger array and
copies the content of previous array into the new array and remaining space in new array for adding
additional elements and this process keeps happening but programmer is not aware of this activity.
88
ArrayList Continued
4. An ArrayList object can only store references of Java Class objects and variables of primitive types
such as int, float, double etc. can not be stored in an ArrayList.
5. An ArrayList object in not synchronized i.e multiple independent threads can access a particular
ArrayList object simultaneously.
1) boolean add(E e): Append a specified element e to the end of the concerned
ArrayList object.
2) void add(int index, E element): Inserts the speicified element at the specified
position in the concerned ArrayList.
3) int capacity(): returns the current capacity of the concerned ArrayList object.
4) void clear(): removes all of the elements from the concerned ArrayList object.
5) boolean contains(Object O): returns true if the concerned ArrayList object holds
the reference of Object O passed as argument.
6) Iterator<E> interator: returns an iterator object to iterate over the elements of the
concerned ArrayList object.
7) E set(int index, E element): Replaces the element at specified position in the list
with specified element
8) int indexOf(Object O): returns the index of first occurrence of element O in
concerned ArrayList.
92
93
94
95
Vector Class
▪ Like ArrayList, Vector generic class provides you a mechanism to implement a
growable list of objects by initially creating a default size array and by creating new
larger size arrays according to requirement similar to ArrayList
▪ Elements can be accessed using index.
▪ Each Vector Class object optimize storage management by maintaining two
parameters capacity, and capacityIncrement. The capacity is always as larger as size
of Vector object. Once the objects are added into Vector, the vector storage
increases in chunks the size of capacityIncrement.
▪ Like ArrayList, this class objects also provide iterator object to traverse its elements
in a sequence.
▪ The main difference between an ArrayList and Vector Class objects is that Vector
Class objects are thread safe i.e. at a particular instant only a single thread can
modify a particular Vector Class object but this not with an ArrayList object.
▪ Most of the utility methods calls in ArrayList and Vector Classes are same.
96
Some of the frequently Vector Class Methods
1) boolean add(E e): Append a specified element e to the end of the concerned Vector
object.
2) void add(int index, E element): Inserts the speicified element at the specified
position in the concerned Vector.
3) int capacity(): returns the current capacity of the concerned Vector object.
4) void clear(): removes all of the elements from the concerned Vector object.
5) boolean contains(Object O): returns true if the concerned Vector object holds the
reference of Object O passed as argument.
6) Iterator<E> interator: returns an iterator object to iterate over the elements of the
concerned Vector object.
7) int indexOf(Object O): returns the index of first occurrence of element O in
concerned ArrayList.
8) E set(int index, E e): replaces the element at specified index position with the
specified element.
98
Stack Class in Java
1) The Stack class represents a last in first out(LIFO) stack of objects.
2) It extends the Vector Class with five operations that allow a Vector to be
treated as a stack.
3) Those five additional operations are mentioned below
4) E peek(): determines the element at the top of stack without removing it.
5) E pop(): removes the object at the top of this stack and returns the value
of this function
6) E push(E item): pushes an item at the top of this stack.
99
100
101
102
PriorityQueue
1) It is a collection in which elements are ordered according to their natural
ordering, or by a comparator provided at Queue construction time
depending upon type of constructor used.
2) The head of this queue is the least element with specified ordering.
3) A priority queue is unbounded, but has an internal capacity governing the
size of the array used to store the elements on the queue.
4) As elements are added into queue it’s capacity grows automatically.
5) The implementation of PriorityQueue is not synchronized there multiple
thread instances shold not access a PriorityQueue instance concurrently
Some most frequently used priority queue methods
1) boolean add(E e): Inserts the specified element in the priority queue.
2) comparator(): Returns the comparator used to order elements in this queue or null is returned if natural
ordering is used.
3) boolean contains(Object O): Returns true if the queue contains the specified element.
4) boolean offer(E e): returns true if the queue contains the specified element.
5) poll(): retrieves and removes the head of this queue or returns null if queue is empty
6) remove(Object O): removes a single instance of the specified element from this queue of null is
returned if queue is empty.
7) Int size(): Size of queue is returned
104
LinkedList overview
• Stores each element in a node
• Each node stores a link to the next and previous nodes
• Insertion and removal are inexpensive
» just update the links in the surrounding nodes
• Linear traversal is inexpensive
• Random access is expensive
» Start from beginning or end and traverse each node while counting
107
LinkedList entries
private static class Entry {
Object element;
Entry next;
Entry previous;
public LinkedList() {
header.next = header.previous = header;
}
108
Some frequently used linked list methods
1) add(E e): The specified element e is appended at the end of the linked list.
2) add(int position, E element): the specified element is inserted at the specified position in the linked
list.
3) contains(Object o): returns true if object o is present in the linked list.
4) get(int position): returns the element at the specified position in the list
5) peek(): retrieves but does not removes the first element of the linked list
6) Remove(): retrieves and then removes the first element of the linked list
7) remove(int position): removes the element present at the specified position in the linked list.
8) set(int position, E e): replaces the element present at the specified position with element e.
109
110
111
112
Set Interface Context
Collection
Set
113
Set Interface
• Same methods as Collection
» different contract - no duplicate entries
• Defines two fundamental methods
» boolean add(Object o) - reject duplicates
» Iterator iterator()
• Provides an Iterator to step through the elements
in the Set
» No guaranteed order in the basic Set interface
» There is a SortedSet interface that extends Set
114
HashSet and TreeSet Context
Collection
Set
HashSet TreeSet
115
HashSet
• Find and add elements very quickly
» uses hashing implementation in HashMap
• Hashing uses an array of linked lists
» The hashCode() is used to index into the array
» Then equals() is used to determine if element is in the
(short) list of elements at that index
• No order imposed on elements
• The hashCode() method and the equals() method
must be compatible
» if two objects are equal, they must have the same
hashCode() value
116
Some most frequently used HashSet methods
1)boolean add(E e): The specified element e is added into the concerned HashSet when the element is not
alerady present.
2) Void clear(): All elements are removed from the concerned HashSet.
3) boolean contains(Object O): returns true if the concerned HashSet contains the specified element.
4) boolean isEmpty(): returns true if the concerned HashSet contains no element.
5) boolean remove(Object O): removes the specified element from the concerned HashSet.
6)int size(): returns the size of the concerned HashSet.
117
118
119
120
TreeSet
• Elements can be inserted in any order
• The TreeSet stores them in order
» Red-Black Trees out of Cormen-Leiserson-Rivest
• An iterator always presents them in order
• Default order is defined by natural order
» objects implement the Comparable interface
» TreeSet uses compareTo(Object o) to sort
• Can use a different Comparator
» provide Comparator to the TreeSet constructor
121
Some most frequently used TreeSet methods
1)boolean add(E e): The specified element e is added into the concerned TreeSet when the element is not
alerady present.
2) Void clear(): All elements are removed from the concerned TreeSet.
3) boolean contains(Object O): returns true if the concerned TreeSet contains the specified element.
4) boolean isEmpty(): returns true if the concerned TreeSet contains no element.
5) boolean remove(Object O): removes the specified element from the concerned TreeSet.
6)int size(): returns the size of the concerned HashSet.
7) E higher(E e): returns the least element in the concerned TreeSet strictly greater than specified element
or null if there is no such element.
122
123
124
125
Linked Hash Set
126
Some most frequently used LinkedHashSet methods
1)boolean add(E e): The specified element e is added into the concerned LinkedHashSet when the
element is not alerady present.
2) Void clear(): All elements are removed from the concerned LinkedHashSet.
3) boolean contains(Object O): returns true if the concerned LinkedHashSet contains the specified
element.
4) boolean isEmpty(): returns true if the concerned LinkedHashSet contains no element.
5) boolean remove(Object O): removes the specified element from the concerned LinkedHashSet.
6)int size(): returns the size of the concerned LinkedHashSet.
127
128
129
130
Map Interface Context
Map
131
Map Interface
• Stores key/value pairs
• Maps from the key to the value
• Keys are unique
» a single key only appears once in the Map
» a key can map to only one value
• Values do not have to be unique
132
HashMap
1)A HashMap is a implementation of Map interface and conceptually its
similar to a Hashtable thus providing a key,value pair type recording of
information.
2)A hashmap is created using following statement:
HashMap<K,V> Map1=new HashMap<K,V> where K may be any valid class
a class for key objects and V may be any class for value objects. E.g
HashMap<String,Integer> Map1=new HashMap<String,Integer> ();
4)V put(key k, value v): Associates the specified value v with specified key in
the HashMap.
5) V remove(Object k): the mapping based on specified key k is removed from
the HashMap.
6) V replace(Key k, Value v): the entry based on key k is replaced if it is
already present in HashMap.
134
135
136
TreeMap
1) A TreeMap is also a key,value mapping based collection for information
storage.
1) ceilingEntry(Key k): returns a key,value pair based entry associated with least key greater than or
equal to the given Key k or null is returned.
2) ceilingKey(Key k): returns a key greater than or equal to the given Key k or null is returned.
3) containsKey(Object k): true is returned if there is mapping in TreeMap containing Key k.
4) containsValue(Object v): true is returned if there is atleast one mapping with value v in TreeMap
5) get(Object k): the value v is returned corresponding to key k is mapping k,v is present in TreeMap
otherwise null is returned.
6) put(Key k, Value v): a mapping corresponding to Key k and Value v is recorded in TreeMap
LinkedHashMap
1) It is an implementation of Map interface based upon the concepts of
Hashtable and linkedlist.
2) This implementation is different from HashMap in that this collections
also maintains a double linkedlist consisting of all key,value pair enteries.
3) Like HashMap, it provides constant time operations.
4) Like HashMap it also allows permits null elements.
5) The implementation of LinkedHashMap is not synchronized.
141
Some frequently used LinkedHashMap Methods