Sunteți pe pagina 1din 68

Methods and Inner

Class
Part II

1
Java
Contents

1 Arguments passing
2 Passing primitive type
3 What is happening?
4 Passing reference type
5 Changing the member variable value of an object reference that is passed
6 Changing array contents in a method
7 Var-args
8 Accessing var-args
9 Overloading
10 Overloading with var-args

2
Java
Contents

11 Initializers
12 Static Initializer
13 Non-Static Initializer
14 Inner class
15 Types of Inner Class
16 Non static inner class
17 Creating InnerClass instance
18 Result of execution
19 Static Inner Class
20 Test your understanding

3
Java
know
• Argument passing
• var-arg
• Method overloading
• Initializers
• Inner classes and static inner classes

4
Java
Be Able To

• Implement method overloading


• Use inner classes and static inner classes

5
Java
Arguments passing
• Arguments passing in java is always ‘pass by
value’.

• Two types of arguments can be passed in a


method call
 -- Primitive type
 -- Reference type

6
Java
Passing primitive type

public class StudentTest{


public static void swap(int reg1,int
reg2){
int temp;
temp=reg1;
reg1=reg2;
reg2=temp; }

Folder 1
7
Java
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
Java
What is happening?

Stack

reg1=20,reg2=10
swap(r1,r2)
r1=10, r2=20 Changes made in swap
main() is not reflected in main()
9
Java
Passing reference type
public class StudentTest{
public static void swap(Student
p,Student q){
Student temp;
temp=p;
p=q;
q=temp;
Folder 2
}

10
Java
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
11
Java
stack

q
p

swap(s1,s2) heap

s2 Mary..

s1 John..
main()

After swap() s1 and s2 of main remains unchanged and p and


q are no longer available.
12
Java
Changing the member variable
value of an object reference that is
passed
public 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
13
Java
stack

p heap
John
change(s1)
Mary
s1
main()

Change made to the member variable ‘name’ reflected in


main().
Prints Mary.
14
Java
Changing array contents in a
method
public class StudentTest{
public static void sort(Student s[]){
Student temp;
for(int i=0;i<s.length-1;i++){
for(int j=i+1;j<s.length;j++){
if( (s[i].getName().compareTo(s[j].getName()))>0
){
temp=s[i];
s[i]=s[j];
s[j]=temp; } Folder 4
15
Java
}}}
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<s1.length;i++){
System.out.println("Name: " +
s1[i].getName());
}
}
16
} Java
stack

s
heap
sort(s1)

0
s1
1 Mary..
main()
John..

Changes made to the array content reflected in the main method.

17
Java
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<s1.length;i++){
System.out.println("Name: " +
s1[i].getName());
}
}
public static void change(Student s[]){
Student temp[]=new Student[1];
temp[0]= new Student("Meena"); Folder 5
s=temp; } } 18
Java
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 variable
length.

19
Java
Accessing var-args
public class Person{
public Person(String name, String…
nicknames)
{
if(nicknames.length!=0){
for(String nm:nicknames)
System.out.println(nm);

System.out.println(nicknames[0]);
} }} Folder 6
20
Java
Can you write main() method
as
public static void
main(String... args)
instead of args[] ?

21
Java
What is the difference between an array and
var-args? (Are both
static void vararg1(int[] i) &
static void vararg2(int… i))
same ?)

Folder 7
22
Java
Overloading
public class CollegeUtility {
public static void
sortStudent(Student s[]){
..} So
many
public static void
sort
sortCollege(College c[]){
method
..} names !

public static void


sortFaculties(Faculty c[])
{..}}
23
Java
public class CollegeUtility {
public static void sort(Student
s[]){..}
public static void sort(College
c[]){..}
public static void sort(Faculty
c[]){..}
public static void sort(Facility
c[]){..}
}
Overloading sort method – much simpler
24
Java
Overloaded method List1:All the methods where the name
resolution and number of arguments of calling
method == name and number of
arguments of called method
Error: No matching
yes
method found List1 is empty Error

no
List2: From list1, find all the
methods that exactly match
the argument type of
calling method.
yes

List2 contains > 1 element

25
Java
no

List2 contains 1 element


yes

no
Matching method found
List3: Find all the methods from
List1 where arguments of
calling methods are
automatically convertible yes
into arguments of called
methods.

List3 contains= 1 element

no
26
Java
no

List3 contains 0 element yes Error

no
List4: Find among the
methods in List 3 methods
which are more specific

yes
List4 contains 1 element Matching method found

no
Error

27
Java
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
}} 28
Java
//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
29
Java
//more specific public static void
public class Fee { main(String[] args)
{
int id;
Fee f1= new
double amtPaid; Fee();
void pay(int id,double amt){ f1.pay(123,400);
this.id=id; }
amtPaid=amt; }
} Look at the conversion
sequence to find out which
void pay(int id,float amt) { argument is more specific.
this.id=id; Slide 34 of Nuts and Bolts
Folder 10
amtPaid=amt; }
//ambiguous
public class StudentManager{
public static void
changeSemester(int id, long sem){

}
public static void
changeSemester(long id, int seam){
… Automatic
conversion
}
public static void main(String str[]){
changeSemester(1,2);
}
}
31
Java
Overloading with var-args
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);
}}
Folder 11

32
Java
static void vararg(int[] i){}
static void vararg(int... x){}
cannot be overloaded.

33
Java
Initializers
• Initializers are blocks of code that are used to
initialize member variables.

a) Static Initializers
b) Non-Static Initializers

34
Java
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 ?

35
Java
Let us say that you initialize
your variables after reading
their 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 in
initializers !

36
Java
I can put that code in
the constructor !

Yes, you can certainly put them in


the constructor. But if you have
more than one constructor then
repeating the same code everywhere
would be a pain. Also note that if
you want to initialize your static
variables in the similar way before
the object is created then static
initializer is the only place !

37
Java
Static Initializer
public class CollegeConstants{
public static final int YEAR_OF_INCEPTION;
public static final String COLLEGE_NAME ;
Static block

static{
/*
Open the file and set the required
YEAR_OF_INCEPTION, COLLEGE_NAME
*/
}
38
Java
Non-Static Initializer
public class OldStudent {
{
private int regNo;
private String name; Non-Static block

{
/*
Open the file and set the required reg_no, name
of each student
*/
}
}
39
Java
To understand what gets called
when, we shall execute the code
give 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

40
Java
static{
System.out.println("static block");
}
public Z(){
System.out.println("Z constructor");
}
public static void main(String st[]){
new Z();
}
}
41
Java
Output:
static block
W constructor
instance block
Z constructor

Can you guess what will be printed


if you comment ‘new Z()’ in
main()?

42
Java
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 is
called outer class.
• Inner class can access all members of the outer class
including private members.
• Based on where the inner class is defined, the inner
class can be classified into two types.

43
Java
Types of Inner Class

• Member class
• Non Static Inner Class or simply inner
class
Note that in some books they don’t
• Static Inner Class
consider static inner classes as
inner classes. They are just
• Local Inner Class considered as nested classes.

• Local named class or simply local inner


class
• Anonymous Inner Class
44
Java
Non static inner class
• Structure:
public class OuterClass{
public class InnerClass{..}
} Can be declared as private, default or protected.
• 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 fields
and methods of the member classes are also available
to other member classes.
45
Java
Creating InnerClass instance
OuterClass out= new OuterClass();
OuterClass.InnerClass in=out.new
InnerClass();
Or
OuterClass.InnerClass in=new
OuterClass().new InnerClass();

Within OuterClass, InnerClass object can be created


by
InnerClass in=new InnerClass();
46
Java
Example: linked list
• Node class can be viewed as inner class of
LinkedList class because Node class as a
standalone class does not make any sense by
itself.
• We will look at implementing a SinglyLinkedList
class 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

47
Java
headNode
public class SinglyLinkedList{
private Node headNode;null
private int noOfNodes=0;

Inner class
class Node {

private Node nextNode;


private String currentObject;

public String toString() {


String s=(String)(currentObject);
return s;
Folder 13
}
} 48
Java
public String insertFirst(Object addobj) {
Node tempNode = new Node();
tempNode.currentObject=addobj;
tempNode
noOfNodes++;
if (headNode==null) First node null
headNode=tempNode;

else {
current=headNode; headNode
headNode=tempNode;
headNode.nextNode = current;} private member of Node class
return
(String)headNode.currentObject;
}
headnode

null

current

tempNode null 49
Java
public String insertLast(Object addobj) {
create
Node create=new Node();
create.currentObject=addobj;
noOfNodes++;
if(headNode==null) First node headNode
headNode=create;
Iterate till the end of
else { the list and get the
Node tempNode = headNode; last node.
while(tempNode.nextNode!=null) {
tempNode = tempNode.nextNode;
}
headNode
tempNode.nextNode=create;}
tempNode
return (String)create.currentObject; create
} 50
Java
public String findNode(int index){Inappropriate index
if(index>noOfNodes) return null;
headNode
Node tempNode = headNode; For index=1
int i=0;
while(i++!=index) 0 1 2
tempNode=tempNode.nextNode;
tempNode returned
return tempNode;}

public Node deleteNode(int index) {


if(index>=noOfNodes) return null;
Deletion of the first node
Node tempNode = headNode; returned
noOfNodes--;
if(index==0){
headNode=headNode.nextNode;
return tempNode;} headNode
51
Java
Iterate till you find the correct
index. tempNode
Node prevNode=null;
int i=0; headNode
while(i++!=index){
0 1 2
prevNode=tempNode; null
tempNode=tempNode.nextNode; } prevNode
Last Node returned
if(i==noOfNodes+1){
prevNode.nextNode=null;
}
else
prevNode.nextNode=tempNode.nextNode;
return tempNode; tempNode
}
} headNode
0 1 2
Deleting index=1 returned
prevNode 52
Java
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!

53
Java
class SampleTest {
public static void main(String args[]) {
SinglyLinkedList s = new SinglyLinkedList();
SinglyLinkedList.Node n;
//Insertion
s.insertFirst("Rama");
s.insertLast("Sita");
s.insertFirst("Hanuman");
s.insertLast("Ravana"); How would you create
an instance of Node
// printing class inside this class?

System.out.println("\nPrinting list
\n"+s.toString());

//Deletion
54
int temp=3; Java
if(n==null)
System.out.println("Invalid ID");
else
System.out.println("Deleting " +n);
//Search
temp=2;
if((n=s.findNode(temp))==null)
System.out.println(" Invalid ID ");
else
System.out.println("Found "+ n);
// printing
System.out.println("\nPrinting list
\n"+s.toString());
}
}

55
Java
Result of execution
Printing list

Hanuman
Rama
Sita
Ravana
Deleting Ravana
Found Sita

Printing list

Hanuman
Rama
Sita
56
Java
In lab find out what .class
files are generated when
you compile the LinkedList
class ?

57
Java
Static Inner Class
• A static inner class is a class that’s a static member of
the outer class which can access only static members of
the outer class(including private members). It is also
called 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();
58
Java
Why static inner class
cannot access instance
members of the outer
class?

59
Java
class Sort{
private static void insertionSort(
int[] a,int s, int temp) {
Sorted array
No. of elements currently in the array New element to be added
int j = s; to ‘a’ in sorted position
while (j > 0 && a[j-1] > temp)
{
a[j] = a[j - 1]; slide elements down to
make room
j--;
}
a[j] = temp;
Sorted array
}
private static int binarySearch(int numbers[],
int key ){
int low,high;
Folder 14
Search element int div=numbers.length;
60
low=0; Java
high=numbers.length-1;
while(true){
div=(low+high)/2;
if(key>numbers[div])
low=div+1;
else if (key<numbers[div])
high=div-1;
else
return div;

if(low> high) return -1;


}
}
static class List{
private int capacity;
private int size;
private int[] nums;
61
Java
List(int capacity){
this.capacity=capacity;
nums=new int[capacity];
}
public void add(int i){
if(capacity==size) {
System.out.println("Over flow");
return;
} private static methods
insertionSort(nums,size,i); of the outer class
size++;
}
public void search(int i){
int pos=-1;
if((pos=binarySearch(nums,i))!=-1)
else
System.out.println("\nNot Found ");
62
} Java
public void display(){
for(int i=0;i<nums.length;i++)
System.out.print(nums[i]+" ");
}}
}
public class Test{
public static void main(String[] args){
Sort.List list= new Sort.List(5);
list.add(10);
list.add(13);
list.add(9);
list.add(12);
list.add(1);
list.display();
list.search(12);
}}
63
Java
Test your understanding
class 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? 64
Java
class B {
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(String
args[]) {new B();}}
Which variable cannot be substituted for “???”
without causing a compile-time error? 65
Java
class F {
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? 66
Java
class Outer {
static class StaticNested {
static final int a = 25; // 1
static final int b; // 2
static int c; // 3
int d; // 4
static {b = 42;} // 5
}
class NonStaticInner {
static final int e = 25; // 6
static final int f; // 7
static int g; // 8
int h; // 9
static {f = 42;} // 10
}}
Compile-time errors are generated at which lines? 67
Java
There are two more types of inner
class: Local and Anonymous
Inner class. We will look at them
after Interfaces.

Thanks !

68
Java

S-ar putea să vă placă și