Date post: | 30-May-2018 |
Category: |
Documents |
Upload: | suresh1130 |
View: | 215 times |
Download: | 0 times |
of 68
8/14/2019 3 2 Classes
1/68
1Java
Methods and Inner
ClassPart II
8/14/2019 3 2 Classes
2/68
2Java
Overloading with var-args10
Overloading9
Accessing var-args8
Var-args7
Changing array contents in a method6
Changing the member variable value of an object reference that is passed5
Passing reference type4
What is happening?3
Passing primitive type2
Arguments passing1
Contents
8/14/2019 3 2 Classes
3/68
3Java
Test your understanding20
Static Inner Class19
Result of execution18
Creating InnerClass instance17
Non static inner class16
Types of Inner Class15
Inner class14
Non-Static Initializer13
Static Initializer12
Initializers11
Contents
8/14/2019 3 2 Classes
4/68
4Java
know
Argument passing
var-arg
Method overloading
Initializers
Inner classes and static inner classes
8/14/2019 3 2 Classes
5/68
5Java
Be Able To
Implement method overloading
Use inner classes and static inner classes
8/14/2019 3 2 Classes
6/68
6Java
Arguments passing
Arguments passing in java is always pass by
value.
Two types of arguments can be passed in amethod call
-- Primitive type -- Reference type
8/14/2019 3 2 Classes
7/68
7Java
Passing primitive type
public class StudentTest{
public static void swap(int reg1,intreg2){
int temp;
temp=reg1;
reg1=reg2;reg2=temp; }
Folder 1
8/14/2019 3 2 Classes
8/68
8Java
public static void main(String args[]){
int r1=10, r2=20;swap(r1,r2);
System.out.println(r1=+ r1);
System.out.println(r2=+r2);
}
}
The program prints r1=10 and r2=20.
8/14/2019 3 2 Classes
9/68
9Java
main()
r1=10, r2=20
swap(r1,r2)
reg1=20,reg2=10
Changes made in swap
is not reflected in main()
Stack
What is happening?
8/14/2019 3 2 Classes
10/68
10Java
Passing reference type
public class StudentTest{public static void swap(Studentp,Student q){
Student temp;temp=p;
p=q;
q=temp;
}Folder 2
8/14/2019 3 2 Classes
11/68
11Java
public static void main(String a[]){
Student s1=new Student(John);Student s2=new Student(Mary);
swap(s1,s2);
System.out.println(s1=+s1.getName());
System.out.println(s2=+ s2.getName()
}
}The program prints :
s1=John
s2=Mary
8/14/2019 3 2 Classes
12/68
12Java
main()
s2s1
swap(s1,s2)
qp
John..
Mary..
stack
heap
After swap() s1 and s2 of main remains unchanged and p and
q are no longer available.
Ch i th b i bl
8/14/2019 3 2 Classes
13/68
13Java
Changing the member variable
value of an object reference that is
passedpublic class StudentTest{public static void change(Student p){
p.setName(Mary); }public static void main(String args[]){
Student s1=new Student(John);
change(s1);System.out.println(s1=+s1.getName());}}
Folder 3
t k
8/14/2019 3 2 Classes
14/68
14Java
main()
s1
change(s1)
p
John
stack
heap
Mary
Change made to the member variable name reflected inmain().
Prints Mary.
8/14/2019 3 2 Classes
15/68
15Java
public class StudentTest{public static void sort(Student s[]){
Student temp;
for(int i=0;i
8/14/2019 3 2 Classes
16/68
16Java
}}}
public static void main(String args[]){
Student s1[]=new Student[2];
s1[0]=new Student("Mary");
s1[1]=new Student("John");
sort(s1);
for(int i=0;i
8/14/2019 3 2 Classes
17/68
17Java
main()
s1
sort(s1)
s
Mary..
John..
stack
heap
Changes made to the array content reflected in the main method.
0
1
8/14/2019 3 2 Classes
18/68
18Java
What is the result when you execute the following?
class StudentTest{
public static void main(String args[]){Student s1[]=new Student[2];s1[0]=new Student("Mary");s1[1]=new Student("John");change(s1);for(int i=0;i
8/14/2019 3 2 Classes
19/68
19Java
Var-args
This is a new feature in 1.5 .
Allows you to specify that a method can take multiple
arguments of same type. The number arguments
may be 0, one or more.void go(int x)
void go(char c, int x)
void go(Animal a)
In a method only the last argument can be of variablelength.
8/14/2019 3 2 Classes
20/68
20Java
Accessing var-args
public class Person{
public Person(String name, Stringnicknames)
{if(nicknames.length!=0){
for(String nm:nicknames)
System.out.println(nm);
System.out.println(nicknames[0]);
} }} Folder 6
8/14/2019 3 2 Classes
21/68
21Java
Can you write main() methodas
public static void
main(String... args)
instead of args[] ?
8/14/2019 3 2 Classes
22/68
22Java
What is the difference between an array and
var-args? (Are bothstatic void vararg1(int[] i) &
static void vararg2(int i))
same ?)
Folder 7
8/14/2019 3 2 Classes
23/68
23Java
Overloading
public class CollegeUtility {
public static voidsortStudent(Student s[]){
..}
public static voidsortCollege(College c[]){
..}
public static voidsortFaculties(Faculty c[])
{..}}
So
many
sort
method
names !
8/14/2019 3 2 Classes
24/68
24Java
public class CollegeUtility {
public static void sort(Students[]){..}
public static void sort(College
c[]){..}public static void sort(Facultyc[]){..}
public static void sort(Facilityc[]){..}
}Overloading sort method much simpler
8/14/2019 3 2 Classes
25/68
25Java
List1:All the methods where the name
and number of arguments of calling
method == name and number of
arguments of called method
List1 is empty Error
List2 contains > 1 element
List2: From list1, find all themethods that exactly match
the argument type ofcalling method.
yes
yes
no
Overloaded method
resolution
Error: No matching
method found
8/14/2019 3 2 Classes
26/68
26Java
no
List3: Find all the methods from
List1 where arguments of
calling methods areautomatically convertibleinto arguments of calledmethods.
List3 contains= 1 element
no
List2 contains 1 element
no
Matching method found
yes
yes
8/14/2019 3 2 Classes
27/68
27Java
no
List3 contains 0 elementyes
Error
no
List4: Find among the
methods in List 3 methods
which are more specific
List4 contains 1 element Matching method found
Error
yes
no
8/14/2019 3 2 Classes
28/68
28Java
Examples//exact match
public class StudentTest{
public static void display(int regno){
System.out.println(Registration No."+regno);
}public static void display(String name){System.out.println(Name. "+name);}
public static void main(String str[]){
Student s1=new Student(Mary);
display(s1.getName());
display(s1.getRegNo());
}}Folder 8
8/14/2019 3 2 Classes
29/68
29Java
//automatic conversion
public class StudentTest{
public static void display(long regno){System.out.println(Registration No."+regno);
}
public static void display(String name){System.out.println(Name. "+name);}
public static void main(String str[]){
Student s1=new Student(Mary);display(s1.getRegNo());
}}
Folder 9
8/14/2019 3 2 Classes
30/68
//more specific
public class Fee {
int id;
double amtPaid;
void pay(int id,double amt){
this.id=id;
amtPaid=amt;
}
void pay(int id,float amt) {
this.id=id;
amtPaid=amt; }
public static voidmain(String[] args){
Fee f1= newFee();
f1.pay(123,400);
}
}
Look at the conversion
sequence to find out whichargument is more specific.
Slide 34 of Nuts and Bolts
Folder 10
http://../Java/mod_Instructor_slides/3.%20Nuts%20and%20Bolts.ppthttp://../Java/mod_Instructor_slides/3.%20Nuts%20and%20Bolts.ppt8/14/2019 3 2 Classes
31/68
31Java
//ambiguous
public class StudentManager{
public static void
changeSemester(int id, long sem){
}
public static voidchangeSemester(long id, int seam){
}
public static void main(String str[]){changeSemester(1,2);}
}
Automatic
conversion
8/14/2019 3 2 Classes
32/68
32Java
class AddVarargs {
static void go(int x, int y){ System.out.println("int,int");}static void go(byte... x){ System.out.println("byte... ");}public static void main(String[] args){
byte b = 5;go(b,b);}}
Overloading with var-args
Folder 11
8/14/2019 3 2 Classes
33/68
33Java
static void vararg(int[] i){}
static void vararg(int... x){}
cannot be overloaded.
8/14/2019 3 2 Classes
34/68
34Java
Initializers
Initializers are blocks of code that are used to
initialize member variables.
a) Static Initializers
b) Non-Static Initializers
8/14/2019 3 2 Classes
35/68
35Java
But I can declare and initialize variables
in same line like this:
class X{
int var=1; }
Why will I require a block of code ?
8/14/2019 3 2 Classes
36/68
36Java
Let us say that you initialize
your variables after readingtheir values from a file.
Reading from a file requires a
sequence of operations at the
minimum - opening a file,
reading and then closing a file
this means a block of java
statements. This cannot be
done in one statement like
yours. So we do this ininitializers !
8/14/2019 3 2 Classes
37/68
37Java
Yes, you can certainly put them in
the constructor. But if you have
more than one constructor thenrepeating the same code everywhere
would be a pain. Also note that if
you want to initialize your static
variables in the similar way beforethe object is created then static
initializer is the only place !
I can put that code in
the constructor !
8/14/2019 3 2 Classes
38/68
38Java
Static Initializer
public class CollegeConstants{
public static final int YEAR_OF_INCEPTION;
public static final String COLLEGE_NAME ;
static{
/*
Open the file and set the required
YEAR_OF_INCEPTION, COLLEGE_NAME*/
}
Static block
Non Static Initializer
8/14/2019 3 2 Classes
39/68
39Java
Non-Static Initializerpublic class OldStudent {
{private int regNo;
private String name;
{/*
Open the file and set the required reg_no, nameof each student
*/
}
}
Non-Static block
8/14/2019 3 2 Classes
40/68
40Java
To understand what gets called
when, we shall execute the codegive below.
public class W{
public W(){
System.out.println("W constructor"); }}
public class Z{
W w= new W();
{
System.out.println("instance block");
} Folder 12
8/14/2019 3 2 Classes
41/68
41Java
static{
System.out.println("static block");}
public Z(){
System.out.println("Z constructor");}
public static void main(String st[]){
new Z();}
}
8/14/2019 3 2 Classes
42/68
42Java
Output:
static block
W constructor
instance block
Z constructor
Can you guess what will be printed
if you comment new Z() in
main()?
8/14/2019 3 2 Classes
43/68
43Java
Inner class
An inner class is a class defined inside the scope of
another class. It is also called Nested class.
The class inside which the inner class is defined iscalled outer class.
Inner class can access all members of the outer classincluding private members.
Based on where the inner class is defined, the inner
class can be classified into two types.
8/14/2019 3 2 Classes
44/68
44Java
Member class
Non Static Inner Class or simply inner
class
Static Inner Class
Local Inner Class
Local named class or simply local innerclass
Anonymous Inner Class
Types of Inner Class
Note that in some books they dont
consider static inner classes as
inner classes. They are just
considered as nested classes.
8/14/2019 3 2 Classes
45/68
45Java
Non static inner class Structure:
public class OuterClass{
public class InnerClass{..}
}
Non static inner class object cannot be created
without a outer class object.
The private fields and methods of the member classes
are available to the enclosing class. The private fieldsand methods of the member classes are also available
to other member classes.
Can be declared as private, default orprotected.
8/14/2019 3 2 Classes
46/68
46Java
OuterClass out= new OuterClass();OuterClass.InnerClass in=out.new
InnerClass();
Or
OuterClass.InnerClass in=newOuterClass().new InnerClass();
Within OuterClass, InnerClass object can be createdby
InnerClass in=new InnerClass();
Creating InnerClass instance
8/14/2019 3 2 Classes
47/68
47Java
Example: linked list Node class can be viewed as inner class of
LinkedList class because Node class as astandalone class does not make any sense by
itself.
We will look at implementing a SinglyLinkedListclass with following options:
Inserting at the head, at the tail
Finding a particular node given an index.
Deleting a particular node given an index.
Printing nodes
8/14/2019 3 2 Classes
48/68
48Java
public class SinglyLinkedList{
private Node headNode;
private int noOfNodes=0;
class Node {
private Node nextNode;private String currentObject;
public String toString() {String s=(String)(currentObject);
return s;
}
}
Inner class
headNode
null
Folder 13
8/14/2019 3 2 Classes
49/68
49Java
public StringinsertFirst(Object addobj) {Node tempNode = new Node();
tempNode.currentObject=addobj;noOfNodes++;
if (headNode==null)headNode=tempNode;
else {
current=headNode;headNode=tempNode;
headNode.nextNode = current;}return
(String)headNode.currentObject;}
First node
tempNode
headNode
headnode
current
tempNode
null
null
null
private member of Node class
bli St i i tL t(Obj t dd bj) {
8/14/2019 3 2 Classes
50/68
50Java
public String insertLast(Object addobj) {Node create=new Node();create.currentObject=addobj;
noOfNodes++;if(headNode==null)headNode=create;
else {
Node tempNode = headNode;while(tempNode.nextNode!=null) {tempNode = tempNode.nextNode;}
tempNode.nextNode=create;}
return (String)create.currentObject;}
create
headNodeFirst node
Iterate till the end ofthe list and get the
last node.
headNode
tempNode
create
public String findNode(int index){Inappropriate index
8/14/2019 3 2 Classes
51/68
51Java
if(index>noOfNodes) return null;
Node tempNode = headNode;
int i=0;while(i++!=index)tempNode=tempNode.nextNode;return tempNode;}
public Node deleteNode(int index) {if(index>=noOfNodes) return null;
Node tempNode = headNode;
noOfNodes--;if(index==0){headNode=headNode.nextNode;return tempNode;}
headNode
0 1
Inappropriate index
For index=1
tempNode returned
Deletion of the first nod
headNode
returned
dIterate till you find the correcti d
8/14/2019 3 2 Classes
52/68
52Java
Node prevNode=null;int i=0;while(i++!=index){
prevNode=tempNode;tempNode=tempNode.nextNode; }
if(i==noOfNodes+1){
prevNode.nextNode=null;}
elseprevNode.nextNode=tempNode.nextNode;return tempNode;}
}
Deleting index=1
headNode
prevNode
0 1 2
Last Node
headNode
prevNode2
tempNode
tempNode
null
returned
returned
index.
8/14/2019 3 2 Classes
53/68
53Java
public String toString() {String s="";
for(Node n=headNode;n!=null;n=n.nextNode)s=s+"\n"+((String)(n.currentObject.toString()));
return s;}}//end of class
This should be pretty straight forward now!
class SampleTest {
8/14/2019 3 2 Classes
54/68
54Java
public static void main(String args[]) SinglyLinkedList s = new SinglyLinkedList();SinglyLinkedList.Node n;
//Insertions.insertFirst("Rama");s.insertLast("Sita");s.insertFirst("Hanuman");
s.insertLast("Ravana");// printingSystem.out.println("\nPrinting list
\n"+s.toString());
//Deletion
int temp=3;
How would you create
an instance of Node
class inside this class?
if(n==null)
8/14/2019 3 2 Classes
55/68
55Java
if(n==null)System.out.println("Invalid ID");
else
System.out.println("Deleting " +n);//Searchtemp=2;if((n=s.findNode(temp))==null)System.out.println(" Invalid ID");
elseSystem.out.println("Found "+ n);
// printingSystem.out.println("\nPrinting list
\n"+s.toString());}
}
Result of execution
8/14/2019 3 2 Classes
56/68
56Java
Result of execution
Printing list
Hanuman
Rama
Sita
Ravana
Deleting Ravana
Found Sita
Printing list
Hanuman
Rama
Sita
8/14/2019 3 2 Classes
57/68
57Java
In lab find out what .class
files are generated when
you compile the LinkedList
class ?
Static Inner Class
8/14/2019 3 2 Classes
58/68
58Java
Static Inner Class A static inner class is a class thats a static member of
the outer class which can access only static members ofthe outer class(including private members). It is alsocalled top-level class.
Structure:
public class OuterClass{public static class InnerClass{} }
Creating instance: Outside the outer class:OuterClass.InnerClass sinner=new OuterClass.InnerClass();
Inside the outer class:InnerClass inner=new InnerClass();
8/14/2019 3 2 Classes
59/68
59Java
Why static inner class
cannot access instance
members of the outer
class?
class Sort{
8/14/2019 3 2 Classes
60/68
60Java
private static void insertionSort(int[] a,int s, int temp) {
int j = s;while (j > 0 && a[j-1] > temp){
a[j] = a[j - 1];j--;}a[j] = temp;}
private static int binarySearch(int numbers[],int key ){
int low,high;int div=numbers.length;
low=0;
No. of elements currently in the array
Sorted arrayNew element to be addedto a in sorted position
slide elements down to
make room
Sorted array
Search elementFolder 14
high=numbers.length-1;
8/14/2019 3 2 Classes
61/68
61Java
while(true){div=(low+high)/2;if(key>numbers[div])
low=div+1;else if (key high) return -1;
}}
static class List{private int capacity;private int size;private int[] nums;
List(int capacity){
8/14/2019 3 2 Classes
62/68
62Java
this.capacity=capacity;nums=new int[capacity];
}
public void add(int i){if(capacity==size) {System.out.println("Over flow");return;
}insertionSort(nums,size,i);size++;}
public void search(int i){
int pos=-1;if((pos=binarySearch(nums,i))!=-1)elseSystem.out.println("\nNot Found ");
}
private static methodsof the outer class
public void display(){
8/14/2019 3 2 Classes
63/68
63Java
public void display(){for(int i=0;i
8/14/2019 3 2 Classes
64/68
64Java
Test your understandingclass E {
E() {System.out.print("E");}
static class Z {Z(){
System.out.print("Z");}}
public static void main(String args[]){
new E.Z();}}What is the result of attempting to compile and run the
program?
class B {
8/14/2019 3 2 Classes
65/68
65Java
private static String s1 = "s1";final String s2 = "s2";
B () {new Z("s5","s6");}static class Z {final String s3 = "s3";static String s4 = "s4";
Z (final String s5, String s6){
System.out.print(???);}}
public static void main(Stringargs[]) {new B();}}Which variable cannot be substituted for ???
without causing a compile-time error?
class F {
8/14/2019 3 2 Classes
66/68
66Java
{public void m1() {Z.m1();}
private static class Y {
private static void m1() {System.out.print("Y.m1 ");}}private static class Z {
private static void m1(){System.out.print("Z.m1 ");Y.m1();
}}
public static void main(String[] args){new F().m1();}}What is the result of attempting to compile and run the
program?
class Outer {
8/14/2019 3 2 Classes
67/68
67Java
{static class StaticNested {
static final int a = 25; // 1
static final int b; // 2static int c; // 3int d; // 4static {b = 42;} // 5
}class NonStaticInner {static final int e = 25; // 6static final int f; // 7
static int g; // 8int h; // 9static {f = 42;} // 10
}}Compile-time errors are generated at which lines?
8/14/2019 3 2 Classes
68/68
There are two more types of inner
class: Local and Anonymous
Inner class. We will look at themafter Interfaces.
Thanks !