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

Lect-5 Methods & Classes

Method overloading allows a class to have multiple methods with the same name but different parameters. Java determines which method to invoke based on the number and types of arguments passed. The document provides examples of overloading methods and constructors. It also discusses parameter passing by value for primitive types and by reference for class types, returning objects from methods, recursion, and access control modifiers like public and private.

Uploaded by

Darshan Patel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Lect-5 Methods & Classes

Method overloading allows a class to have multiple methods with the same name but different parameters. Java determines which method to invoke based on the number and types of arguments passed. The document provides examples of overloading methods and constructors. It also discusses parameter passing by value for primitive types and by reference for class types, returning objects from methods, recursion, and access control modifiers like public and private.

Uploaded by

Darshan Patel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

CS-201/CS-261

Object Oriented Design &


Programming/Lab
Method Overloading
• It is legal for a class to have two or more
methods with the same name.

• However, Java has to be able to uniquely


associate the invocation of a method with its
definition relying on the number and types of
arguments.

• Therefore the same-named methods must be


distinguished:
1) by the number of arguments, or
2) by the types of arguments

Overloading and inheritance are two ways to


implement polymorphism.
Example: Overloading
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
Example: Overloading
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;

// call all versions of test()


ob.test(); No parameters
ob.test(10); a: 10
ob.test(10, 20); a and b: 10 20
result = ob.test(123.25); Doublt a: 123.25
System.out.println("Result of ob.test(123.25): "
+ result); Result of ob.test (123.25):
} 15190.5625
}
Example: Overloading
// Automatic type conversions apply to overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}

// Overload test for two integer parameters.


void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}

// overload test for a double parameter and return


type
void test(double a) {
System.out.println("Inside test(double) a: " + a);
}
}
Example: Overloading
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;

ob.test(); No parameters
ob.test(10, 20); a and b: 10 20

ob.test(i); Inside test (double) a: 88


ob.test(123.2); Inside test (double) a: 123.2
}
}
Constructor Overloading
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
Box() {
width = -1; height = -1; depth = -1;
}
Box(double len) {
width = height = depth = len;
}
double volume() { return width * height *
depth; }
}
Constructor Overloading
/* Here, Box defines three constructors to initialize
the dimensions of a box various ways.
*/
class Box {
double width, height, depth;

// constructor used when all dimensions specified


Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
Objects as parameters
// Objects may be passed to methods.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equalTo(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
} class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);

System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));

System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));


}
Objects as parameters
class Box {
double width;
double height;
double depth;

// construct clone of an object


Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
} class OverloadCons2 {
public static void main(String args[]) {
... // create boxes using the various constructors
// compute and
Box return
mybox1 volume
= new Box(10, 20, 15);
double volume() {
Box mybox2 = new Box();
return width
Box mycube = *new
* height depth;
Box(7);
}
} Box myclone = new Box(mybox1);

double vol;
// get volume of clone
vol = myclone.volume();
System.out.println("Volume of clone is " + vol);
}
}
Parameter Passing
• Two types of variables:
1) simple types
2) class types

• Two corresponding ways of how the arguments


are passed to methods:
1) by value a method receives a copy of the
original value; parameters of simple types

2) by reference a method receives the


memory address of the original value, not the
value itself; parameters of class types
Call by value
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.print("a and b before call:
“);
System.out.println(a + " " + b);
ob.meth(a, b);
System.out.print("a and b after call: ");
System.out.println(a + " " + b);
}
}
Call by Reference
• As the parameter hold the same address as the argument,
changes to the object inside the method do affect the object
used by the argument:

class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);

System.out.print("ob.a and ob.b before call: “);


System.out.println(ob.a + " " + ob.b);

ob.meth(ob);

System.out.print("ob.a and ob.b after call: ");


System.out.println(ob.a + " " + ob.b);
}
}
Call by Reference
// Objects are passed through their references.

class Test {
int a, b;

Test(int i, int j) {
a = i;
b = j;
}

// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
}
}
Returning Objects
• A method can return any type of data, including class types.

class Test {
int a;

Test(int i) {
a = i;
}

Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}
}
Returning Objects
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;

ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);

ob2 = ob2.incrByTen();
System.out.println("ob2.a after second
increase: “ + ob2.a);
}
}
Recursion
• A recursive method is a method that calls itself:

1) all method parameters and local variables are allocated on


the stack

2) arguments are prepared in the corresponding parameter


positions

3) the method code is executed for the new arguments

4) upon return, all parameters and variables are removed


from the stack

5) the execution continues immediately after the invocation


point
Activation Records
Example: Recursion
class Factorial {
int fact(int n) {
if (n==1) return 1;
return fact(n-1) * n;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.print("Factorial of 5 is ");
System.out.println(f.fact(5));
} }
Access Control
• Java’s access modifier – Public, Private,
Protected
• Protected applied only when inheritance is
invoked
• When a member of a class is modified by
Public, then that member can be accessed
by any other code.
• When a member of a class is modified by
Private, then that member can only be
accessed by other members of its class.
Access Control
class Test {
int a; // default access
public int b; // public access
private int c; // private access

// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c;
}
}
Access Control
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();

// These are OK, a and b may be accessed directly


ob.a = 10;
ob.b = 20;

// This is not OK and will cause an error


// ob.c = 100; // Error!

// You must access c through its methods


ob.setc(100); // OK

System.out.println("a, b, and c: " + ob.a + " " +


ob.b + " " + ob.getc());
}
}
Revisiting Stack Class
class Stack {
private int stck[] = new int[10];
private int tos;

Stack() {
tos = -1;
}

void push(int item) {


if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}

int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
}
Revisiting Stack Class
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();

// push some numbers onto the stack


for(int i=0; i<10; i++) mystack1.push(i);
for(int i=10; i<20; i++) mystack2.push(i);

// pop those numbers off the stack


System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());

System.out.println("Stack in mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());

mystack1.tos = -2; Both are illegal


mystack2.stck[3] = 100; statements
}
}
static
• Normally, a class member must be accessed only
in conjunction with an object of its class.
• A static class member can be used
independently of any object of that class.
• It is possible to create a member that can be
used by itself, without reference to a specific
instance.
• When a member is declared static, it can be
accessed before any objects of its class are
created, and without reference to any object.
Static variable
• Instance variables declared as static as,
essentially, global variables.
• When objects of its class are declared, no copy
of a static variable is made.
• Instead, all instances of the class share the same
static variable.
Static Method
• Methods declared as static have several
restrictions:
– They can only directly call other static
methods
– They can only directly access static data
– They can not refer to this or super in any
way
Static
class UseStatic {
static int a = 3;
static int b;

static void meth(int x) {


System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}

static {
System.out.println("Static block initialized.");
b = a * 4;
}

public static void main(String args[]) {


meth(42);
}
}
Static
• Outside the class, static methods &
variables can be used independently of any
object
classname.method()
• A static variable can be accessed in the
same way – using dot operator
Static
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}

class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
final
• A field declared as final will prevent its
contents from being modified, making it,
essentially, a constant.
• Two ways to declare
– Give it a value when it is declared
– Assign it a value within a constructor
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
Nested & Inner Classes
• Define a class within another class –
Nested class
• If class B is defined within A, then B does
not exist independently of A.
• The scope of a nested class is bounded by
the scope of its enclosing class.
• A nested class has access to the members,
including private members of the class, in
which it is nested.
• However, the enclosing class does not have
access to members of the nested class
Nested & Inner Classes
• Types of nested class – static & non-static
• Static nested class are seldom used
• Non static nested class aka Inner class
• Inner class has access to all of the
variables and methods its outer class and
may refer to them directly in the same way
that other non-static members of the
outer class do.
Nested & Inner Classes
class Outer {
int outer_x = 100;

void test() {
Inner inner = new Inner();
inner.display();
}

// this is an innner class


class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
Nested & Inner Classes
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
class Inner {
int y = 10; // y is local to Inner
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
void showy() {
System.out.println(y); // error, y not known here!
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
class Outer {
Nested & Inner Classes
int outer_x = 100;

void test() {
for(int i=0; i<10; i++) {
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
Inner inner = new Inner();
inner.display();
} display: outer_x = 100
} display: outer_x = 100
} display: outer_x = 100
display: outer_x = 100
class InnerClassDemo { display: outer_x = 100
display: outer_x
public static void main(String args[]) ={ 100
display: outer_x = 100
Outer outer = new Outer();
outer.test(); display: outer_x = 100
} display: outer_x = 100
} display: outer_x = 100
String Handling
• String is probably the most commonly used class in
Java's class library. The obvious reason for this is that
strings are a very important part of programming.

• The first thing to understand about strings is that


every string you create is actually an object of type
String. Even string constants are actually String
objects.

• For example, in the statement


System.out.println("This is a String,
too");
the string "This is a String, too" is a String constant
String Handling

• Java defines one operator for String


objects: +.
• It is used to concatenate two strings. For
example, this statement
• String myString = "I" + " like " +
"Java.";
results in myString containing
"I like Java."
String Handling
• The String class contains several methods that you can use.
Here are a few. You can
• test two strings for equality by using
equals( ). You can obtain the length of a string by calling the
length( ) method. You can obtain the character at a
specified index within a string by calling charAt( ). The
general forms of these three methods are shown here:

// Demonstrating some String methods.


class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: "
+ strOb1.length());
String Handling
System.out.println ("Char at index 3 in strOb1: " +
strOb1.charAt(3));
if(strOb1.equals(strOb2))

System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
} }

This program generates the following output:


Length of strOb1: 12
Char at index 3 in strOb1: s
strOb1 != strOb2
strOb1 == strOb3
QUIZ 1

Queue class
- having insertion & deletion operations
- Use only constructors
- Define QuizQueue class to use Queue class

You might also like