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

Lecture 06 - Methods and Classes

This document discusses various object-oriented programming concepts in Java including method overloading, constructor overloading, using objects as parameters, cloning objects, argument passing, and returning objects. It provides examples to demonstrate each concept. Method overloading allows methods within the same class to have the same name but different parameters. Constructor overloading similarly allows constructors to be differentiated by their parameters. Objects can be passed as parameters to methods and changes made to the object within the method will affect the original object. Objects can also be cloned by passing one object to another object's constructor. In Java, primitive types are passed by value while objects are passed by reference. Returning objects from methods is possible since objects are dynamically allocated using new.

Uploaded by

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

Lecture 06 - Methods and Classes

This document discusses various object-oriented programming concepts in Java including method overloading, constructor overloading, using objects as parameters, cloning objects, argument passing, and returning objects. It provides examples to demonstrate each concept. Method overloading allows methods within the same class to have the same name but different parameters. Constructor overloading similarly allows constructors to be differentiated by their parameters. Objects can be passed as parameters to methods and changes made to the object within the method will affect the original object. Objects can also be cloned by passing one object to another object's constructor. In Java, primitive types are passed by value while objects are passed by reference. Returning objects from methods is possible since objects are dynamically allocated using new.

Uploaded by

Muhammad Tayyab
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

CSE205: Object Oriented

Programming
Lecture # 06: Methods and Classes

Muhammad Imran
(Based on Java, The Complete Reference)
http://www.secscourses.tk

1
Outline
• Overloading Methods
• Overloading Constructors
• Using Objects as Parameters
• Construct Clone
• Argument Passing
• Returning Objects
• Access Control
• static
• final

2
Overloading Methods

• It is possible to define two or more methods


within the same class that share the same name,
as long as their parameter declarations are
different.
• Such methods are called overloaded, and the
process is referred to as method overloading.
• Method overloading is one of the ways of
implementing polymorphism.

3
Overloading Methods
• When an overloaded method is invoked, Java uses the type and/or
number of arguments as its guide to determine which version of the
overloaded method to actually call.
• If an exact type-match is not found, Java will employ its automatic
type conversions.
• While overloaded methods may have different return types, the
return type alone is insufficient to distinguish two versions of a
method.

4
Overloading Methods
// Demonstrate method // Overload test for two
overloading. integer parameters.
class OverloadDemo { void test(int a, int b) {
void test() { System.out.println("a and
System.out.println("No b: " + a + " " + b);
parameters"); }
} // overload test for a double
// Overload test for one parameter
integer parameter. double test(double a) {
void test(int a) { System.out.println("double
System.out.println("a: " + a: " + a);
a); return a*a;
} }
}
5
Overloading Methods
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.2);
System.out.println("Result of ob.test(123.2): " + result);
}
} No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625 6
Overloading Methods (Read Online)

https://beginnersbook.com/2013/05/method-
overloading/

7
Overloading Constructors
/* Here, Box defines three constructors to initialize
the dimensions of a box various ways.
*/
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
8
Overloading Constructors
// 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;
}
} 9
Overloading Constructors
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
} Volume of mybox1 is 3000.0
} Volume of mybox2 is -1.0
Volume of mycube is 343.0
10
Using 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 equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
11
Using Objects as Parameters
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.equals(ob2));

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


}
}

ob1 == ob2: true


ob1 == ob3: false 12
Construct Clone of an Object
• We may want to construct a new object so that it is
initially the same as some existing object.

• To do this, we must define a constructor that takes an


object of its class as a parameter.

13
Construct Clone of an Object
// Here, Box allows one object to initialize another.
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;
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w; height = h; depth = d;
} 14
Construct Clone of an Object
// 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;
}
} 15
Construct Clone of an Object
class OverloadCons2 {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Box myclone = new Box(mybox1);
double vol;
vol = mybox1.volume(); // get volume of first box
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume(); // get volume of second box
System.out.println("Volume of mybox2 is " + vol);
vol = mycube.volume(); // get volume of cube
System.out.println("Volume of cube is " + vol);
vol = myclone.volume(); // get volume of clone Volume of mybox1 is 3000.0
System.out.println("Volume of clone is " + vol); Volume of mybox2 is -1.0
} Volume of cube is 343.0
Volume of clone is 3000.0
} 16
Argument Passing
• There are two ways that a computer language can pass an argument
to a method.
• Call-by-value
 Copies the value of an argument into the formal parameter of the method.
 Changes made to the parameter of the method have no effect on the
argument.
• Call-by-reference
 A reference to an argument (not the value of the argument) is passed to the
parameter.
 Inside the method, this reference is used to access the actual argument
specified in the call.
 Changes made to the parameter will affect the argument used to call the
method.

17
Argument Passing
• In Java, when we pass a primitive type to a method, it is passed by
value.
• When we pass an object to a method, it is implicitly passed by
reference.
 When we create a variable of a class type, we are only creating a reference to
an object.
 When we pass this reference to a method, the parameter that receives it will
refer to the same object as that referred to by the argument.
 Changes made to the object inside the method do affect the object used as an
argument.

18
Argument Passing
// Objects are passed by reference.
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;
}
}
19
Argument Passing
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);

System.out.println("ob.a and ob.b before call: " +


ob.a + " " + ob.b);

ob.meth(ob);

System.out.println("ob.a and ob.b after call: " +


ob.a + " " + ob.b);
}
} ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
20
Returning Objects
• Since all objects are dynamically allocated using new, we don’t need
to worry about an object going out-of-scope when the method in
which it was created terminates.
• The object will continue to exist as long as there is a reference to it
somewhere in our program.
• When there are no references to it, the object will be reclaimed the
next time garbage collection takes place.

21
Returning Objects
// Returning an object.
class Test {
int a;
Test(int i) {
a = i;
}

Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}
}

22
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);
}
}
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22
23
Access Control

• How a member can be accessed is determined by the access

specifier that modifies its declaration.

• Java’s access specifiers are public, private, protected, and a

default access level.

• When no access specifier is used, then by default the

member of a class is public within its own package, but

cannot be accessed outside of its package.

24
Access Control
/* Demonstrates the difference between public, private, and
default.*/
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;
}
} 25
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());
}
} 26
static
• We may want to define a class member that will be used
independently of any object of that class.
• To create such a member, precede its declaration with the keyword
static.
• Instance variables declared as static are, 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.

27
static
• Methods declared as static have several restrictions:
 They can only call other static methods.
 They must only access static data.
 They cannot refer to this or super in any way.
• If we need to do computation in order to initialize our static
variables, we can declare a static block which gets executed exactly
once, when the class is first loaded.

28
static
// Demonstrate static variables, methods, and blocks.
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 method is called Static block initialized.
} x = 42
} a=3
b = 12
29
final
• A variable can be declared as final. Doing so prevents its
contents from being modified.
• This means that we must initialize a final variable when it is
declared.
• For example:
 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;
• Variables declared as final do not occupy memory on a per-
instance basis.

30
Nested and Inner Classes
• It is possible to define a class within another class; such classes are
known as nested classes
• If class B is defined within class A, then B does not exist
independently of A
• 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 the members
of the nested class.
• A nested class is a member of its enclosing class.

31
Nested and Inner Classes
// Demonstrate an inner class. class InnerClassDemo {
class Outer { public static void main(String
int outer_x = 100; args[]) {
Outer outer = new Outer();
void test() { outer.test();
Inner inner = new Inner(); }
inner.display(); }
}

// this is an inner class


class Inner {
void display() {
System.out.println("display:
outer_x = " + outer_x);
}
}
}

32
Recommended Readings
• Page # 129 to 160, Chapter # 7: A Closer Look at Methods
and Classes from Herbert Schildt, Java: The Complete
Reference, J2SETM 9th Edition

33

You might also like