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

Chapter 7 - A Closer Look On Methods and Classes

nsu3

Uploaded by

Abid Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Chapter 7 - A Closer Look On Methods and Classes

nsu3

Uploaded by

Abid Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Chapter 7: A Closer

Look on Methods and


Classes
Dr. Mohammad Rashedur Rahman
Method Overloading
• In Java, 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.
• When this is the case, the methods are said to be overloaded, and the
process is referred to as method overloading.
• Method overloading is one of the ways that Java supports polymorphism.
• 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.
• Thus, overloaded methods must differ in the type and/or number of their
parameters
Method Overloading (Cont..)
• 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 (Cont..)
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.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
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; }
}
Passing Objects as Parameters
Access Control: Data Hiding and
• Encapsulation
Java provides control over the visibility of variables and
methods.
• Encapsulation, safely sealing data within the capsule of the
class. Prevents programmers from relying on details of class
implementation, so you can update without worry
• For example, allowing access to data only through a well
defined
set of methods, you can prevent the misuse of that data.
• Thus, when correctly implemented, a class creates a “black
box” which may be used, but the inner workings of which are
not open to tampering
• Helps in protecting against accidental or wrong usage.
Access Modifiers: Public, Private, Protected
• Public: keyword applied to a class, makes it
available/visible everywhere. Applied to a method or
variable, completely visible.

• When a member of a class is modified by public,


then that member can be accessed by any other
code.

• Default(No visibility modifier is specified): it behaves


like public in its package and private in other
packages.
Access Modifiers: Public, Private, Protected
• Private fields or methods for a class
only visible within that class. Private
members are not visible within
subclasses, and are not inherited.
• When a member of a class is
specified as private, then that
member can only be accessed by
other members of its class
• Protected members of a class are
visible within the class, subclasses
and also within all classes that are in
the same package as that class.
Use of Static Keyword in Class
• Normally, a class member must be accessed only in conjunction with an
object of its class.
• However, it is possible to create a member that can be used by itself,
without reference to a specific instance.
• To create such a member, precede its declaration with the keyword static.
• When a member is declared static, it can be accessed before any objects
of its class are created, and without reference to any object.
• You can declare both methods and variables to be static.
• The most common example of a static member is main( ).
• main( ) is declared as static because it must be called before any objects
exist.
Restrictions of 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.
• Methods declared as static have several restrictions:
• They can only directly call other static methods.
• They can only directly access static data.
• They cannot refer to this or super in any way. (The keyword super relates to
inheritance and is described in the next chapter.)
Example 1: Static (Call Inside Class)
• As soon as the UseStatic class is
loaded, all of the static statements
are run.
• First, a is set to 3, then the static
block executes, which prints a
message and then initializes b to a*4
or 12.
• Then main( ) is called, which calls
meth( ), passing 42 to x.
• The three println( ) statements refer
to the two static variables a and b, as
well as to the local variable x.
Example 2: Static (Calling from
Outside)
• Outside of the class in which they are
defined, static methods and variables
can be used independently of any
object.
• To do so, you need only specify the
name of their class followed by the dot
operator.
• For example, if you wish to call a static
method from outside its class, you can
do so using the following general form:
• classname.method( )
• Here, classname is the name of the
class in which the static method is
declared.
Final Keyword
• A field can be declared as final. Doing so prevents its contents from being
modified, making it, essentially, a constant.
• This means that you must initialize a final field when it is declared. You
can do this in one of two ways:
• First, you can give it a value when it is declared. Second, you can assign it
a value within a constructor. The first approach is the most common.
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
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 cope 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
// Primitive types are passed by value.
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
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
class Test { affect the object used by the argument:
int a, b; class CallByRef {
Test(int i, int j) { public static void main(String args[]) {
a = i;
b = j;
Test ob = new Test(15, 20);
} System.out.print("ob.a and ob.b before call: “);
// pass an object System.out.println(ob.a + " " + ob.b);
void meth(Test o) { ob.meth(ob);
o.a *= 2; System.out.print("ob.a and ob.b after call: ");
o.b /= 2; System.out.println(ob.a + " " + ob.b);
}
}
}
}
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
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));
} }
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
• 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."
• 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());
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
Object Creation

• A variable is declared to refer to the objects of type/class String:


String s;
• The value of s is null; it does not yet refer to any object.
• A new String object is created in memory with initial “abc” value:
• String s = new String(“abc”);
• Now s contains the address of this new object.
Object Destruction
• A program accumulates memory through its execution.
• Two mechanism to free memory that is no longer need by the
program:
1) manual – done in C/C++
2) automatic – done in Java
• In Java, when an object is no longer accessible through any variable, it
is eventually removed from the memory by the garbage collector.
• Garbage collector is parts of the Java Run-Time Environment.

You might also like