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

Unit 2

Uploaded by

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

Unit 2

Uploaded by

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

UNIT II

METHODS:
• Methods are subroutines that manipulate the data defined by class and in some cases,
control access to that data
• The only required elements of a method declaration are the method's return type, name,
a pair of parentheses, (), and a body between braces, {}.
• Two of the components of a method declaration comprise the method signature—the
method's name and the parameter types.
• Method declarations have six components, in order:
1. Modifiers—such as public, private
2. The return type—the data type of the value returned by the method, or void if
the method does not return a value.
3. The method name—the rules for field names apply to method names as well,
but the convention is a little different.
4. The parameter list in parenthesis—a comma-delimited list of input parameters,
preceded by their data types, enclosed by parentheses, (). If there are no
parameters, you must use empty parentheses.
5. The method body, enclosed between braces—the method's code, including the
declaration of local variables, goes here.
• General Form:
type name(parameter-list) {
// body of method
}
• The type of data returned by a method must be compatible with the return type specified
by the method.
• The variable receiving the value returned by a method must also be compatible with the
return type specified for the method.
return value; //Here, value is the value returned.

Returning from a method:


• 2 conditions can cause a method to return
1. When the method’s closing brace is encountered
2. When a return statement is executed.
• There are 2 forms of return
1. One for use in void methods (which do not return a value)
2. Other for returning values
• In a void method, we can terminate a method by using the following form of return:
return;
• When this statement executes, program control returns to the caller, skipping any
remaining code in the method.
For ex:

void sample( ){
for(int i=0; i<10; i++){
if(i==5)
return; //stop at 5
System.out.println(i);
}
}
• The for loop will only run from 0 to 5 because once i equals 5, the method returns.

Returning a Value:
• Methods return a value to the calling routing using this form of return:
return value;
• This from can be used only with methods that have a non-void return type.

OUTPUT:
Using Parameters:
• Value passed to a method is called an argument. Variable that receives the argument is
called a parameter.
• Parameters are declared inside the parentheses that follow the method’s name.
For ex:

class ckNum{
//return true if x is even
boolean isEven(int x){
if((x%2)==0) return true;
else return false;
}
}
Class Demo{
public static void main(String[ ] args){
ckNum e=new ckNum();
if(e.isEven(10))
System.out.println(“10 is even”);
if(e.isEven(9))
System.out.println(“9 is even”);
}
}
OUTPUT:
10 is even
• In the program isEven( ) is called twice, each time a different value is passed.
• When isEven( ) is called the first time, it is passed the value 10. Thus, when isEven( )
begins executing, the parameter x receives the value 10.
• In the second call, it is passed the value 9. Thus, when isEven( ) begins executing, the
parameter x receives the value 9.

Constructors
• It can be tedious to initialize all of the variables in a class each time an instance is
created.
• Java allows objects to initialize themselves when they are created. This automatic
initialization is performed through a special type of method called Constructor which
is used to initialize the object
• A constructor initializes an object immediately upon creation
Rules for creating java constructor:
o It has the same name as the class in which it resides and is syntactically similar
to a method.
o They have no explicit return type.
Types of java constructors:
• There are two types of constructors:
o Default constructor (no-arg constructor)
o Parameterized constructor
Default Constructor:
• Constructor which does not take any argument is called default constructor.
• All classes have constructors, whether you define one or not, because Java
automatically provides a default constructor.
• However, once you define your own constructor, the default constructor is no longer
used
Parameterized Constructors:
• Constructor which takes one or more arguments is called parameterized constructor.
The finalize( ) Method
• By using finalization, you can define specific actions that will occur when an object is
just about to be reclaimed by the garbage collector.
• To add a finalizer to a class, you simply define the finalize( ) method.
• The Java run time calls that method whenever it is about to recycle an object of that
class. Inside the finalize( ) method, actions that must be performed before an object is
destroyed will be specified.
• The garbage collector runs periodically, checking for objects that are no longer
referenced by any running state or indirectly through other referenced objects

• The keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class
• It is important to understand that finalize( ) is only called just prior to garbage
collection.
• It is not called when an object goes out-of-scope, for example. This means that you
cannot know when—or even if—finalize( ) will be executed

The this Keyword


• The this keyword can be used inside any method to refer to the current object. That is,
this is always a reference to the object on which the method was invoked
• The use of this is redundant, but perfectly correct. Inside Box( ), this will always refer
to the invoking object. While it is redundant in this case, this is useful in other contexts
Instance Variable Hiding
• It is illegal in Java to declare two local variables with the same name inside the same
or enclosing scopes
• Interestingly, you can have local variables, including formal parameters to methods,
which overlap with the names of the class’ instance variables
• When a local variable has the same name as an instance variable, the local variable
hides the instance variable
• For example, here is another version of Box( ), which uses width, height, and depth for
parameter names and then uses this to access the instance variables by the same name

• Use this to overcome the instance variable hiding

The new Operator


• new operator has this general form:
class_var = new class_name(arg_list);
• class_var is a variable of the class type being created.
• The class_name is the name of the class that is being instantiated
• The class_name followed by a parenthesized argument list specifies the constructor for
the class.
• If a class does not define its own constructor, new will use the default constructor
supplied by Java
• The new can be used to create an object of any class type.
• It returns a reference to the newly created object, which is assigned to class-var
Controlling Access to Class Members
• As you know, encapsulation links data with the code that manipulates it. However,
encapsulation provides another important attribute: access control.
• How a member can be accessed is determined by the access specifier that modifies its
declaration.
• Java supplies a rich set of access specifiers. Some aspects of access control are related
mostly to inheritance or packages. (A package is, essentially, a grouping of classes.)
• Member access control is achieved through the use of three access specifiers/modifiers
are public, private, and protected. Java also defines a default access level. protected
applies only when inheritance is involved
• When a member of a class is modified by the public specifier, then that member can be
accessed by any other code
• When a member of a class is specified as private, then that member can only be
accessed by other members of its class.
For example,

• Member c is given private access. This means that it cannot be accessed by code outside
of its class. So, inside the AccessTest class, c cannot be used directly. It must be
accessed through its public methods: setc( ) and getc( )
Pass Objects to Methods
• So far, we have only been using primitive types such as int as parameters to methods.
However, it is both correct and common to pass objects to methods.
For example,

• The equals( ) method inside Test compares two objects for equality and returns the
result. That is, it compares the invoking object with the one that it is passed. If they
contain the same values, then the method returns true. Otherwise, it returns false

How Arguments are Passed


• There are two ways in which an argument can be passed to a subroutine.
1. Call-by-value:
▪ Copies the value of an argument into the formal parameter of the
subroutine.
▪ Therefore, changes made to the parameter of the subroutine have no
effect on the argument.
2. Call-by-reference:
▪ Reference to an argument (not the value of the argument) is passed to
the parameter
▪ Inside the subroutine, 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 subroutine.
• Example for call-by-value
• The operations that occur inside meth( ) have no effect on the values of a and b used
in the call; their values here did not change to 30 and 10.

• Example for call-by-reference


• In this case, the actions inside meth( ) have affected the object used as an argument

Returning Objects
• A method can return any type of data, including class types that you create.
• For example

• Returning user defined object


• Each time getErrorInfo( ) is invoked, a new Err object is created, and a reference to
it is returned to the calling routine.

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.
• When Java encounters a call to an overloaded method, it simply executes the version
of the method whose parameters match the arguments used in the call.
Example,
• test( ) is overloaded four times
• In some cases, Java’s automatic type conversions can play a role in overload
resolution.
Example,
• This version of OverloadDemo does not define test(int). Therefore, when test( )
is called with an integer argument inside Overload, no matching method is found.
• Java can automatically convert an integer into a double
• Java will employ its automatic type conversions only if no exact match is found.

• Overloaded methods may have different return types, the return type alone is
insufficient to distinguish two versions of a method.
Example,
Overloading Constructors
• Like methods, constructors can also be overloaded
For example,

• MyClass( ) is overloaded in 4 ways, each constructing an object differently.


• The proper constructor is called based on the parameters specified when new is
executed.

• Constructor overloading allows one object to initialize another


For example,
Recursion
• Recursion is the process of a method calling itself and a method that calls itself is said
to be recursive
• Recursion is the process of defining something in terms of itself.
Example,
• The point at which the recursive call is not made is called base case

• The classic example of recursion is the computation of the factorial of a number. The
factorial of a number N is the product of all the whole numbers between 1 and N.
• When fact( ) is called with an argument of 1, the function returns 1; otherwise, it returns
the product of fact(n–1)*n. To evaluate this expression, fact( ) is called with n–1. This
process repeats until n equals 1 and the calls to the method begin returning.

Understanding static
• 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.
static Variables
• 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.
• General form of accessing static variable is
Classname.static_variablename;
• For example,
MyTimer.count = 10;
• Example 1 shows differences between a static variable and an instance variable
• y is accessed through its class name
Example 2

static Methods
• Methods declared as static are, essentially, global methods.
• They are called independently of any object. A static method is called through its class
name
• For example,
// use a static method.
class StaticMeth {
static int val = 1024; // a static variable
• Methods declared as static have several restrictions:
o They can only call other static methods.
o They must only access static data.
o They cannot refer to this or super in any way.

static Blocks
• Java allows to declare a static block.
• A static block is executed when the class is first loaded.
• Thus, it is executed before the class can be used for any other purpose
For example,
Varargs: Variable Length Arguments
• Java has included a feature that simplifies the creation of methods that need to take
a variable number of arguments. This feature is called varargs and it is short for
variable-length arguments.
• A method that takes a variable number of arguments is called a variable-arity
method, or simply a varargs method
• A variable-length argument is specified by three periods (...). For example, here is
how vaTest( ) is written using a vararg:
static void vaTest(int ... v) {
• This syntax tells the compiler that vaTest( ) can be called with zero or more arguments.
As a result, v is implicitly declared as an array of type int[ ]

• There are two important things to notice about this program.


o First, as explained, inside vaTest( ), v is operated on as an array. This is because
v is an array. The ... syntax simply tells the compiler that a variable number of
arguments will be used, and that these arguments will be stored in the array
referred to by v.
o Second, in main( ), vaTest( ) is called with different numbers of arguments,
including no arguments at all.
o In the case of no arguments, the length of the array is zero
• Variable-length parameter must be the last parameter declared by the method.
For example,
This method declaration is perfectly acceptable:

int doIt(int a, int b, double c, int ... vals) {


• The first three arguments used in a call to doIt( ) are matched to the first three
parameters. Then, any remaining arguments are assumed to belong to vals.
• The following declaration is incorrect:

int doIt(int a, int b, double c, int ... vals, boolean stopFlag) { // Error!
• Here, there is an attempt to declare a regular parameter after the varargs parameter,
which is illegal.
• There is one more restriction to be aware of: there must be only one varargs parameter.
• For example, this declaration is also invalid:
int doIt(int a, int b, double c, int ... vals, double ... morevals) { // Error!
• The attempt to declare the second varargs parameter is illegal.

Overloading Vararg Methods


• You can overload a method that takes a variable-length argument. For example, the
following program overloads vaTest( ) three times:
• This program illustrates both ways that a varargs method can be overloaded.
o First, the types of its vararg parameter can differ. This is the case for vaTest(int
...) and vaTest(boolean ...).
o The second way to overload a varargs method is to add a normal parameter.
This is what was done with vaTest(String, int ...). In this case, Java uses both
the number of arguments and the type of the arguments to determine which
method to call.
Varargs and Ambiguity
• It is possible to create an ambiguous call to an overloaded varargs method.
• For example, consider the following program:
• In this program, the overloading of vaTest( ) is perfectly correct. However, this
program will not compile because of the following call:
vaTest(); // Error: Ambiguous!
• Because the vararg parameter can be empty, this call could be translated into a call to
vaTest(int ...) or vaTest(boolean ...). Both are equally valid. Thus, the call is inherently
ambiguous.
• Here is another example of ambiguity:

• Although the parameter lists of vaTest( ) differ, there is no way for the compiler to
resolve the following call:
vaTest(1)
• Does this translate into a call to vaTest(int ...), with one varargs argument, or into a
call to vaTest(int, int ...) with no varargs arguments? There is no way for the compiler
to answer this question. Thus, the situation is ambiguous.

Introducing Nested and Inner Classes


• It is possible to define a class within another class; such classes are known as nested
classes.
• The scope of a nested class is bounded by the scope of its enclosing class. Thus, 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 that is declared directly within its enclosing class scope is a member of
its enclosing class.
• There are two types of nested classes: static and non-static.
o static nested class is one that has the static modifier applied. Because it is static,
it must access the members of its enclosing class through an object. That is, it
cannot refer to members of its enclosing class directly.
o The most important type of nested class is the inner class. An inner class is a
non-static nested class. It has access to all of the variables and methods of its
outer class and may refer to them directly.

• Class Inner is defined within the scope of class Outer. Therefore, any code in class
Inner can directly access the variable outer_x
• An instance method display( ) is defined inside Inner. This method displays outer_x
• The main( ) method of InnerClassDemo creates an instance of class Outer and
invokes its test( ) method. That method creates an instance of class Inner and the
display( ) method is called.
• An instance of Inner can be created only within the scope of class Outer. The compiler
generates an error message if any code outside of class Outer attempts to instantiate
class Inner
• However, its possible to create an instance of Inner outside of Outer by qualifying its
name with Outer, as in Outer.Inner.
• An inner class has access to all of the members of its enclosing class, but the reverse is
not true.
• Members of the inner class are known only within the scope of theinner class and may
not be used by the outer class.
For example
• It is possible to define inner classes within any block scope.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy