SlideShare a Scribd company logo
1 of 31
Download to read offline
Page 1 of 31
Class Notes on Class Objects and Methods (Week - 3)
Contents:- Defining a class, Data fields Declaration, Creating Objects, Accessing Class Members, Constructors, Methods
Overloading, access specifiers, operators, control statements & loops, array, finalize and garbage collection, this
keyword, use of objects as parameter & methods returning objects, call by value & call by reference, static variables &
methods, garbage collection, nested and inner classes.
What Is a Class?
In the real world, you'll often find many individual objects all of the same kind. There may be thousands of
other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of
blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an
instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are
created.
The following Bicycle class is one possible implementation of a bicycle:
class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue) {
cadence = newValue;
}
void changeGear(int newValue) {
gear = newValue;
}
void speedUp(int increment) {
speed = speed + increment;
}
void applyBrakes(int decrement) {
speed = speed - decrement;
}
void printStates() {
System.out.println("cadence:" +
cadence + " speed:" +
speed + " gear:" + gear);
}
}
The syntax of the Java programming language will look new to you, but the design of this class is based on the
previous discussion of bicycle objects. The fields cadence, speed, and gear represent the object's state, and the
methods (changeCadence, changeGear, speedUp etc.) define its interaction with the outside world.
You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete
application; it's just the blueprint for bicycles that might be used in an application. The responsibility of
creating and using new Bicycle objects belongs to some other class in your application.
Page 2 of 31
Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their methods:
class BicycleDemo {
public static void main(String[] args) {
// Create two different
// Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
// Invoke methods on
// those objects
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();
bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
}
}
The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles:
cadence:50 speed:10 gear:2
cadence:40 speed:20 gear:3
Declaring Member Variables
There are several kinds of variables:
 Member variables in a class—these are called fields.
 Variables in a method or block of code—these are called local variables.
 Variables in method declarations—these are called parameters.
The Bicycle class uses the following lines of code to define its fields:
public int cadence;
public int gear;
public int speed;
Field declarations are composed of three components, in order:
1. Zero or more modifiers, such as public or private.
2. The field's type.
3. The field's name.
The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int). The public
keyword identifies these fields as public members, accessible by any object that can access the class.
Page 3 of 31
Objects
A typical Java program creates many objects, which as you know, interact by invoking methods. Through these
object interactions, a program can carry out various tasks, such as implementing a GUI, running an animation,
or sending and receiving information over a network. Once an object has completed the work for which it was
created, its resources are recycled for use by other objects.
The following two statements of BicycleDemo class create two separate Bicycle objects.
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
Creating Objects
As you know, a class provides the blueprint for objects; you create an object from a class. Each of the following
statements taken from the BicycleDemo program creates an object and assigns it to a variable:
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
The 2 line creates an object of the Bicycle class.
Each of these statements has three parts (discussed in detail below):
1. Declaration: The code set in bold are all variable declarations that associate a variable name with an object
type.
2. Instantiation: The new keyword is a Java operator that creates the object.
3. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
Declaring a Variable to Refer to an Object
Previously, you learned that to declare a variable, you write:
type name;
This notifies the compiler that you will use name to refer to data whose type is type. With a primitive variable,
this declaration also reserves the proper amount of memory for the variable.
You can also declare a reference variable on its own line. For example:
Point originOne;
If you declare originOne like this, its value will be undetermined until an object is actually created and
assigned to it. Simply declaring a reference variable does not create an object. For that, you need to use the
new operator, as described in the next section. You must assign an object to originOne before you use it in
your code. Otherwise, you will get a compiler error.A variable in this state, which currently references no
object, can be illustrated as follows (the variable name, originOne, plus a reference pointing to nothing):
Page 4 of 31
Instantiating a Class
The new operator instantiates a class by allocating memory for a new object and returning a reference to that
memory. The new operator also invokes the object constructor.
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you
are creating an "instance" of a class, therefore "instantiating" a class.
The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor
provides the name of the class to instantiate.
The new operator returns a reference to the object it created. This reference is usually assigned to a variable
of the appropriate type, like:
Point originOne = new Point(23, 94);
Initializing an Object
Here's the code for the Point class:
class Point {
public int x = 0;
public int y = 0;
//constructor
Point(int a, int b) {
x = a;
y = b;
}
}
This class contains a single constructor. You can recognize a constructor because its declaration uses the same
name as the class and it has no return type. The constructor in the Point class takes two integer arguments, as
declared by the code (int a, int b). The following statement provides 23 and 94 as values for those arguments:
Point originOne = new Point(23, 94);
The result of executing this statement can be illustrated in the next figure:
Page 5 of 31
Here's the code for the Rectangle class, which contains four constructors:
class Rectangle {
int width = 0;
int height = 0;
Point origin;
// four constructors
Rectangle() {
origin = new Point(0, 0);
}
Rectangle(Point p) {
origin = p;
}
Rectangle(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
// a method for moving the rectangle
void move(int x, int y) {
origin.x = x;
origin.y = y;
}
// a method for computing the area of the rectangle
int getArea() {
return width * height;
}
}
Each constructor lets you provide initial values for the rectangle's size and width, using both primitive and
reference types. If a class has multiple constructors, they must have different signatures. The Java compiler
differentiates the constructors based on the number and the type of the arguments. When the Java compiler
encounters the following code, it knows to call the constructor in the Rectangle class that requires a Point
argument followed by two integer arguments:
Rectangle rectOne = new Rectangle(originOne, 100, 200);
This calls one of Rectangle's constructors that initializes origin to originOne. Also, the constructor sets width to
100 and height to 200. Now there are two references to the same Point object—an object can have multiple
references to it, as shown in the next figure:
Page 6 of 31
The following line of code calls the Rectangle constructor that requires two integer arguments, which provide
the initial values for width and height. If you inspect the code within the constructor, you will see that it
creates a new Point object whose x and y values are initialized to 0:
Rectangle rectTwo = new Rectangle(50, 100);
The Rectangle constructor used in the following statement doesn't take any arguments, so it's called a no-
argument constructor:
Rectangle rect = new Rectangle();
All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler
automatically provides a no-argument constructor, called the default constructor. This default constructor
calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If
the parent has no constructor (Object does have one), the compiler will reject the program.
Defining Methods
Here is an example of a typical method declaration:
public double calculateAnswer(double wingSpan, int numberOfEngines,
double length, double grossTons) {
//do the calculation here
}
The only required elements of a method declaration are the method's return type, name, a pair of
parentheses, (), and a body between braces, {}.
More generally, method declarations have six components, in order:
1. Modifiers—such as public, private, and others you will learn about later.
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. An exception list—to be discussed later.
6. The method body, enclosed between braces—the method's code, including the declaration of local
variables, goes here.
Modifiers, return types, and parameters will be discussed later in this lesson. Exceptions are discussed in a
later lesson.
Definition: Two of the components of a method declaration comprise the method signature—the method's name and
the parameter types.
Page 7 of 31
The signature of the method declared above is:
calculateAnswer(double, int, double, double)
Naming a Method
Although a method name can be any legal identifier, code conventions restrict method names. By convention,
method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase,
followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following
words should be capitalized. Here are some examples:
 run
 runFast
 getBackground
 getFinalData
 compareTo
 setX
 isEmpty
Typically, a method has a unique name within its class. However, a method might have the same name as
other methods due to method overloading.
Overloading Methods
The Java programming language supports overloading methods, and Java can distinguish between methods
with different method signatures. This means that methods within a class can have the same name if they
have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled
"Interfaces and Inheritance").
Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so
on) and that contains a method for drawing each data type. It is cumbersome to use a new name for each
method—for example, drawString, drawInteger, drawFloat, and so on. In the Java programming language, you
can use the same name for all the drawing methods but pass a different argument list to each method. Thus,
the data drawing class might declare four methods named draw, each of which has a different parameter list.
public class DataArtist {
...
public void draw(String s) {
...
}
public void draw(int i) {
...
}
public void draw(double f) {
...
}
public void draw(int i, double f) {
...
}
}
Page 8 of 31
Overloaded methods are differentiated by the number and the type of the arguments passed into the method.
In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require
different argument types.
You cannot declare more than one method with the same name and the same number and type of arguments,
because the compiler cannot tell them apart.
The compiler does not consider return type when differentiating methods, so you cannot declare two
methods with the same signature even if they have a different return type.
Note: Overloaded methods should be used sparingly, as they can make code much less readable.
Constructors
A constructor is a special method that is used to initialize a newly created objectand is called just after the
memory is allocated for the objectIt can be used to initialize the objects ,to required ,or default valuesat the
time of object creationIt is not mandatory for the coder to write a constructor for the class
If no user defined constructor is provided for a class, compiler initializes member variables to its default
values.
 numeric data types are set to 0
 char data types are set to null character(‘’)
 reference variables are set to null
In order to create a Constructor observe the following rules
1. It has the same name as the class
2. It should not return a value not even void
class Demo{
int value1; int value2;
Demo(){
value1 = 10; value2 = 20;
System.out.println("Inside Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
d1.display();
}
}
Page 9 of 31
Step 2) Save , Run & Compile the code. Observe the output.
constructor overloading
Constructor overloading is a technique in Java in which a class can have any number of constructors that differ
in parameter lists. The compiler differentiates these constructors by taking into account the number of
parameters in the list and their type
Examples of valid constructors for class Account are
 Account(int a);
 Account (int a,int b);
 Account (String a,int b);
class Demo{
int value1;
int value2;
/*Demo(){
value1 = 10;
value2 = 20;
System.out.println("Inside 1st Constructor");
}*/
Demo(int a){
value1 = a;
System.out.println("Inside 2nd Constructor");
}
Demo(int a,int b){
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
Demo d2 = new Demo(30);
Demo d3 = new Demo(30,40);
d1.display();
d2.display();
d3.display();
}
}
Every class has a default Constructor. Default Constructor for class Demo is Demo(). In case you do not provide
this constructor the compiler creates it for you and initializes the variables to default values. You may choose
to override this default constructor and initialize variables to your desired values .But if you specify a
parametrized constructor like Demo(int a) ,and want to use the default constructor Demo(), it is mandatory
for you to specify it. In other words, in case your Constructor is overridden , and you want to use the default
constructor , its need to be specified.
Access Specifiers
Page 10 of 31
One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a
class and making this class available only through methods. In this way the chance of making accidental
mistakes in changing values is minimized. Java allows you to control access to classes, methods, and fields via
so-called access specifiers.
Java offers four access specifiers, listed below in decreasing accessibility:
 public
 protected
 default (no specifier)
 private
We look at these access specifiers in more detail.
public
public classes, methods, and fields can be accessed from everywhere. The only constraint is that a file with
Java source code can only contain one public class whose name must also match with the filename. If it exists,
this public class represents the application or the applet, in which case the public keyword is necessary to
enable your Web browser or appletviewer to show the applet. You use public classes, methods, or fields only
if you explicitly want to offer access to these entities and if this access cannot do any harm. An example of a
square determined by the position of its upper-left corner and its size:
public class Square { // public class
public x, y, size; // public instance variables
}
protected
protected methods and fields can only be accessed within the same class to which the methods and fields
belong, within its subclasses, and within classes of the same package, but not from anywhere else. You use the
protected access level when it is appropriate for a class's subclasses to have access to the method or field, but
not for unrelated classes.
default (no specifier)
If you do not set access to specific level, then such a class, method, or field will be accessible from inside the
same package to which the class, method, or field belongs, but not from outside this package. This access-level
is convenient if you are creating packages. For example, a geometry package that contains Square and Tiling
classes, may be easier and cleaner to implement if the coordinates of the upper-left corner of a Square are
directly available to the Tiling class but not outside the geometry package.
private
private methods and fields can only be accessed within the same class to which the methods and fields
belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. So,
the private access specifier is opposite to the public access specifier. It is mostly used for encapsulation: data
are hidden within the class and accessor methods are provided. An example, in which the position of the
upper-left corner of a square can be set or obtained by accessor methods, but individual coordinates are not
accessible to the user.
Page 11 of 31
public class Square { // public class
private double x, y // private (encapsulated) instance variables
public setCorner(int x, int y) { // setting values of private fields
this.x = x;
this.y = y;
}
public getCorner() { // setting values of private fields
return Point(x, y);
}
}
Summary of Access Specifiers
The following table summarizes the access level permitted by each specifier.
Situation public protected default private
Accessible to class
from same package?
yes yes yes no
Accessible to class
from different package?
yes no, unless it is a subclass no no
Note the difference between the default access which is in fact more restricted than the protected access.
Without access specifier (the default choice), methods and variables are accessible only within the class that
defines them and within classes that are part of the same package. They are not visible to subclasses unless
these are in the same package. protected methods and variables are visible to subclasses regardless of which
package they are in.
Java Control Flow Statements
Java Control statements control the order of execution in a java program, based on data values and
conditional logic. There are three main categories of control flow statements;
 Selection statements: if, if-else and switch.
 Loop statements: while, do-while and for.
 Transfer statements: break, continue.
We use control statements when we want to change the default sequential order of execution
Selection Statements - The If Statement
The if statement executes a block of code only if the specified expression is true. If the value is false, then the
if block is skipped and execution continues with the rest of the program. You can either have a single
statement or a block of code within an if statement. Note that the conditional expression must be a Boolean
expression.
The simple if statement has the following syntax:
if (<conditional expression>)
<statement action>
Below is an example that demonstrates conditional execution based on if statement condition.
Page 12 of 31
public class IfStatementDemo {
public static void main(String[] args) {
int a = 10, b = 20;
if (a > b)
System.out.println("a > b");
if (a < b)
System.out.println("b > a");
}
}
Output
b > a
The If-else Statement
The if/else statement is an extension of the if statement. If the statements in the if statement fails, the
statements in the else block are executed. You can either have a single statement or a block of code within if-
else blocks. Note that the conditional expression must be a Boolean expression.
The if-else statement has the following syntax:
if (<conditional expression>)
<statement action>
else
<statement action>
Below is an example that demonstrates conditional execution based on if else statement condition.
public class IfElseStatementDemo {
public static void main(String[] args) {
int a = 10, b = 20;
if (a > b) {
System.out.println("a > b");
} else {
System.out.println("b > a");
}
}
}
Output
b > a
Switch Case Statement
The switch case statement, also called a case statement is a multi-way branch with several choices. A switch is
easier to implement than a series of if/else statements. The switch statement begins with a keyword, followed
by an expression that equates to a no long integral value. Following the controlling expression is a code block
that contains zero or more labeled cases. Each label must equate to an integer constant and each must be
unique. When the switch statement executes, it compares the value of the controlling expression to the values
Page 13 of 31
of each case label. The program will select the value of the case label that equals the value of the controlling
expression and branch down that path to the end of the code block. If none of the case label values match,
then none of the codes within the switch statement code block will be executed. Java includes a default label
to use in cases where there are no matches. We can have a nested switch within a case block of an outer
switch.
Its general form is as follows:
switch (<non-long integral expression>) {
case label1: <statement1>
case label2: <statement2>
…
case labeln: <statementn>
default: <statement>
} // end switch
When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit
in the middle of the switch statement code block, you must insert a break statement, which causes the
program to continue executing after the current code block.
Below is a java example that demonstrates conditional execution based on nested if else statement condition
to find the greatest of 3 numbers.
public class SwitchCaseStatementDemo {
public static void main(String[] args) {
int a = 10, b = 20, c = 30;
int status = -1;
if (a > b && a > c) {
status = 1;
} else if (b > c) {
status = 2;
} else {
status = 3;
}
switch (status) {
case 1:
System.out.println("a is the greatest");
break;
case 2:
System.out.println("b is the greatest");
break;
case 3:
System.out.println("c is the greatest");
break;
default:
System.out.println("Cannot be determined");
}
}
}
Output
c is the greatest
Page 14 of 31
Iteration Statements - While Statement
The while statement is a looping construct control statement that executes a block of code while a condition is
true. You can either have a single statement or a block of code within the while loop. The loop will never be
executed if the testing expression evaluates to false. The loop condition must be a boolean expression.
The syntax of the while loop is
while (<loop condition>)
<statements>
Below is an example that demonstrates the looping construct namely while loop used to print numbers from 1
to 10.
public class WhileLoopDemo {
public static void main(String[] args) {
int count = 1;
System.out.println("Printing Numbers from 1 to 10");
while (count <= 10) {
System.out.println(count++);
}
}
}
Output
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
Do-while Loop Statement
The do-while loop is similar to the while loop, except that the test is performed at the end of the loop instead
of at the beginning. This ensures that the loop will be executed at least once. A do-while loop begins with the
keyword do, followed by the statements that make up the body of the loop. Finally, the keyword while and
the test expression completes the do-while loop. When the loop condition becomes false, the loop is
terminated and execution continues with the statement immediately following the loop. You can either have a
single statement or a block of code within the do-while loop.
The syntax of the do-while loop is
Page 15 of 31
do
<loop body>
while (<loop condition>);
Below is an example that demonstrates the looping construct namely do-while loop used to print numbers
from 1 to 10.
public class DoWhileLoopDemo {
public static void main(String[] args) {
int count = 1;
System.out.println("Printing Numbers from 1 to 10");
do {
System.out.println(count++);
} while (count <= 10);
}
}
Output
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
Below is an example that creates A Fibonacci sequence controlled by a do-while loop
public class Fibonacci {
public static void main(String args[]) {
System.out.println("Printing Limited set of Fibonacci Sequence");
double fib1 = 0;
double fib2 = 1;
double temp = 0;
System.out.println(fib1);
System.out.println(fib2);
do {
temp = fib1 + fib2;
System.out.println(temp);
fib1 = fib2; //Replace 2nd with first number
fib2 = temp; //Replace temp number with 2nd number
} while (fib2 < 5000);
}
}
Output
Printing Limited set of Fibonacci Sequence
Page 16 of 31
0.0
1.0
1.0
2.0
3.0
5.0
8.0
13.0
21.0
34.0
55.0
89.0
144.0
233.0
377.0
610.0
987.0
1597.0
2584.0
4181.0
6765.0
For Loops
The for loop is a looping construct which can execute a set of instructions a specified number of times. It’s a
counter controlled loop.
The syntax of the loop is as follows:
for (<initialization>; <loop condition>; <increment expression>)
<loop body>
The first part of a for statement is a starting initialization, which executes once before the loop begins. The
<initialization> section can also be a comma-separated list of expression statements. The second part of a for
statement is a test expression. As long as the expression is true, the loop will continue. If this expression is
evaluated as false the first time, the loop will never be executed. The third part of the for statement is the
body of the loop. These are the instructions that are repeated each time the program executes the loop. The
final part of the for statement is an increment expression that automatically executes after each repetition of
the loop body. Typically, this statement changes the value of the counter, which is then tested to see if the
loop should continue. All the sections in the for-header are optional. Any one of them can be left empty, but
the two semicolons are mandatory. In particular, leaving out the <loop condition> signifies that the loop
condition is true. The (;;) form of for loop is commonly used to construct an infinite loop.
Below is an example that demonstrates the looping construct namely for loop used to print numbers from 1 to
10.
public class ForLoopDemo {
public static void main(String[] args) {
System.out.println("Printing Numbers from 1 to 10");
Page 17 of 31
for (int count = 1; count <= 10; count++) {
System.out.println(count);
}
}
}
Output
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
Transfer Statements - Continue Statement
A continue statement stops the iteration of a loop (while, do or for) and causes execution to resume at the top
of the nearest enclosing loop. You use a continue statement when you do not want to execute the remaining
statements in the loop, but you do not want to exit the loop itself.
The syntax of the continue statement is
continue; // the unlabeled form
continue <label>; // the labeled form
You can also provide a loop with a label and then use the label in your continue statement. The label name is
optional, and is usually only used when you wish to return to the outermost loop in a series of nested loops.
Below is a program to demonstrate the use of continue statement to print Odd Numbers between 1 to 10.
public class ContinueExample {
public static void main(String[] args) {
System.out.println("Odd Numbers");
for (int i = 1; i <= 10; ++i) {
if (i % 2 == 0)
continue;
// Rest of loop body skipped when i is even
System.out.println(i + "t");
}
}
}
Output
Odd Numbers
1
Page 18 of 31
3
5
7
9
Break Statement
The break statement transfers control out of the enclosing loop ( for, while, do or switch statement). You use a
break statement when you want to jump immediately to the statement following the enclosing control
structure. You can also provide a loop with a label, and then use the label in your break statement. The label
name is optional, and is usually only used when you wish to terminate the outermost loop in a series of nested
loops.
The Syntax for break statement is as shown below;
break; // the unlabeled form
break <label>; // the labeled form
Below is a program to demonstrate the use of break statement to print numbers Numbers 1 to 10.
public class BreakExample {
public static void main(String[] args) {
System.out.println("Numbers 1 - 10");
for (int i = 1;; ++i) {
if (i == 11)
break;
// Rest of loop body skipped when i is even
System.out.println(i + "t");
}
}
}
Output
Numbers 1 – 10
1
2
3
4
5
6
7
8
9
10
finalize method
finalize method in java is a special method much like main method in java. finalize() is called before Garbage
collector reclaim the Object, its last chance for any object to perform cleanup activity i.e. releasing any system
resources held, closing connection if open etc. Main issue with finalize method in java is its not guaranteed by
Page 19 of 31
JLS that it will be called by Garbage collector or exactly when it will be called, for example an object may wait
indefinitely after becoming eligible for garbage collection and before its finalize() method gets called. similarly
even after finalize gets called its not guaranteed it will be immediately collected. Because of above reason it
make no sense to use finalize method for releasing critical resources or perform any time critical activity inside
finalize. It may work in development in one JVM but may not work in other JVM. In this java tutorial we will
see some important points about finalize method in Java, How to use finalize method, what to do and what
not to do inside finalize in Java.
Garbage Collection
The Java virtual machine's heap stores all objects created by a running Java application. Objects are created by
the new, newarray, anewarray, and multianewarray instructions, but never freed explicitly by the code.
Garbage collection is the process of automatically freeing objects that are no longer referenced by the
program.
This chapter does not describe an official Java garbage-collected heap, because none exists. As mentioned in
earlier chapters, the Java virtual machine specification does not require any particular garbage collection
technique. It doesn't even require garbage collection at all. But until infinite memory is invented, most Java
virtual machine implementations will likely come with garbage-collected heaps. This chapter describes various
garbage collection techniques and explains how garbage collection works in Java virtual machines.
Accompanying this chapter on the CD-ROM is an applet that interactively illustrates the material presented in
the chapter. The applet, named Heap of Fish, simulates a garbage-collected heap in a Java virtual machine.
The simulation--which demonstrates a compacting, mark-and-sweep collector--allows you to interact with the
heap as if you were a Java program: you can allocate objects and assign references to variables. The simulation
also allows you to interact with the heap as if you were the Java virtual machine: you can drive the processes
of garbage collection and heap compaction. At the end of this chapter, you will find a description of this applet
and instructions on how to use it.
Why Garbage Collection?
The name "garbage collection" implies that objects no longer needed by the program are "garbage" and can
be thrown away. A more accurate and up-to-date metaphor might be "memory recycling." When an object is
no longer referenced by the program, the heap space it occupies can be recycled so that the space is made
available for subsequent new objects. The garbage collector must somehow determine which objects are no
longer referenced by the program and make available the heap space occupied by such unreferenced objects.
In the process of freeing unreferenced objects, the garbage collector must run any finalizers of objects being
freed.
In addition to freeing unreferenced objects, a garbage collector may also combat heap fragmentation. Heap
fragmentation occurs through the course of normal program execution. New objects are allocated, and
unreferenced objects are freed such that free portions of heap memory are left in between portions occupied
by live objects. Requests to allocate new objects may have to be filled by extending the size of the heap even
though there is enough total unused space in the existing heap. This will happen if there is not enough
contiguous free heap space available into which the new object will fit. On a virtual memory system, the extra
paging (or swapping) required to service an ever growing heap can degrade the performance of the executing
program. On an embedded system with low memory, fragmentation could cause the virtual machine to "run
out of memory" unnecessarily.
Page 20 of 31
Garbage collection relieves you from the burden of freeing allocated memory. Knowing when to explicitly free
allocated memory can be very tricky. Giving this job to the Java virtual machine has several advantages. First,
it can make you more productive. When programming in non-garbage-collected languages you can spend
many late hours (or days or weeks) chasing down an elusive memory problem. When programming in Java you
can use that time more advantageously by getting ahead of schedule or simply going home to have a life.
A second advantage of garbage collection is that it helps ensure program integrity. Garbage collection is an
important part of Java's security strategy. Java programmers are unable to accidentally (or purposely) crash
the Java virtual machine by incorrectly freeing memory.
A potential disadvantage of a garbage-collected heap is that it adds an overhead that can affect program
performance. The Java virtual machine has to keep track of which objects are being referenced by the
executing program, and finalize and free unreferenced objects on the fly. This activity will likely require more
CPU time than would have been required if the program explicitly freed unnecessary memory. In addition,
programmers in a garbage-collected environment have less control over the scheduling of CPU time devoted
to freeing objects that are no longer needed.
this keyword
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this
keyword. this 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. You can use this anywhere a reference to an object of the
current class' type is permitted.
To better understand what this refers to, consider the following version of Box( ):
// A redundant use of this.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
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, one of which is explained in the next
section.
Instance Variable Hiding
As you know, 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. However, when a local variable has the same name as an instance
variable, the local variable hides the instance variable.
This is why width, height, and depth were not used as the names of the parameters to the Box( ) constructor
inside the Box class. If they had been, then width would have referred to the formal parameter, hiding the
instance variable width. While it is usually easier to simply use different names, there is another way around
this situation. Because this lets you refer directly to the object, you can use it to resolve any name space
collisions that might occur between instance variables and local variables. 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:
Page 21 of 31
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
A word of caution: The use of this in such a context can sometimes be confusing, and some programmers are
careful not to use local variables and formal parameter names that hide instance variables. Of course, other
programmers believe the contrary—that it is a good convention to use the same names for clarity, and use
this to overcome the instance variable hiding. It is a matter of taste which approach you adopt.
Although this is of no significant value in the examples just shown, it is very useful in certain situations.
This is an extract from the book: Java 2 - The Complete Reference by Herbert Schildt.
Using Objects as Parameters
So far we have only been using simple types as parameters to methods. However, it is both correct and
common to pass objects to methods. For example, consider the following short program:
// 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;
}
}
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));
}
}
This program generates the following output:
ob1 == ob2: true
ob1 == ob3: false
As you can see, 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. Notice that the parameter o in equals( ) specifies Test as its
Page 22 of 31
type. Although Test is a class type created by the program, it is used in just the same way as Java’s built-in
types. One of the most common uses of object parameters involves constructors. Frequently you will want to
construct a new object so that it is initially the same as some existing object. To do this, you must define a
constructor that takes an object of its class as a parameter. For example, the following version of Box allows
one object to initialize another:
// 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;
}
// 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;
}
}
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;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
Page 23 of 31
vol = mycube.volume();
System.out.println("Volume of cube is " + vol);
// get volume of clone
vol = myclone.volume();
System.out.println("Volume of clone is " + vol);
}
}
As you will see when you begin to create your own classes, providing many forms of constructor methods is
usually required to allow objects to be constructed in a convenient and efficient manner.
Can a java method return an object? Why constructors don’t have a return type?
Absolutely. Make sure the method is labeled as returning an object
i.e
public Object objectMethod(...){
...
return (theObject);
}
Constructors don't have a return type because they simply "construct" an object. In that sense, they are
already returning an object. Constructors implicitly returns an object, they don’t have any return type not
even void.
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call
by value. The changes being done in the called method, is not affected in the calling method.
In case of call by value original value is not changed. Let's take a simple example:
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7.
8.
9. public static void main(String args[]){
10. Operation op=new Operation();
11.
12. System.out.println("before change "+op.data);
13. op.change(500);
14. System.out.println("after change "+op.data);
15.
16. }
17. }
Output:before change 50
after change 50
Page 24 of 31
Another Example of call by value in java
In case of call by reference original value is changed if we made changes in the called method. If we pass
object in place of any primitive value, original value will be changed. In this example we are passing
object as a value. Let's take a simple example:
1. class Operation2{
2. int data=50;
3.
4. void change(Operation op){
5. op.data=op.data+100;//changes will be in the instance variable
6. }
7.
8.
9. public static void main(String args[]){
10. Operation2 op=new Operation2();
11.
12. System.out.println("before change "+op.data);
13. op.change(op);//passing object
14. System.out.println("after change "+op.data);
15.
16. }
17. }
Output:before change 50
after change 150
Modifiers: final and static
A number of modifier keywords can be placed in declarations of methods and variables, and sometimes in
declarations of classes, to provide extra information or restriction on the methods or variables. Here we shall
only discuss the final and static keywords.
 The final Modifier
 The static Modifier
 The Geometrical Shapes Example
The final Modifier
The final modifier keyword makes that the programmer cannot change the value anymore. The actual
meaning depends on whether it is applied to a class, a variable, or a method. We look at these three cases in
more detail.
final Classes
A final class cannot have subclasses. An example:
public final class MathConstants {
...
}
This skeleton defines a class called MathConstants that is publicly accessible but cannot be subclassed.
final Variables
A final variable cannot be changed once it is initialized, In the above class of mathematical constants you can
for example define a numerical approximation of pi by
public final static double PI = 3.141592654;
Page 25 of 31
It is a convention, but not obligatory, to capitalize the name of a final object.
final Methods
A final method cannot be overridden by subclasses. There are two reasons for introducing such a method:
1. Disallowing subclasses to change the meaning of the method;
2. Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code.
In the class of mathematical constants you could define a final method to generate a random constant.
public final static randomNumber() {
...
}
The static Modifier
A variable or method that is shared by all instances of a class is called a class variable or class method. You
recognize such a variable in Java by the static keyword in the declaration. A class variable will instantiate only
one copy of the variable for the whole class instead of a separate copy for each instance of a class. A class
variable belongs to a class, not to an instance of the class.
You can refer to a class variable either through an instance of the class (like a normal instance variable) or
through the full class name of the form classname.variable.
A class method can be referred to through an instance of the class (like a normal method) or through the full
class name of the form classname.method. In fact, a class is an object of the special class Class, so this naming
system is consistent.
You can look at the examples above for how to use class variables and class methods. You can also look at the
example worked out below.
The Geometrical Shapes Example
We shall give an example of the Shape class with the subclasses Circle and Square. In this example you can
practice your knowledge of modifiers and access specifiers.
MathConstants.java
A class for mathematical constants that cannot be subclassed and contains the mathematical constant pi.
public final class MathConstants {
public final static double PI = 3.141592654; // constant pi
}
ShapeCounter.java
A class for counting the number of geometrical objects that cannot be subclassed and does not allow direct
access to the variable that holds in fact the number of shapes; instead, accessor methods are provided to
classes in the same package to which this class belongs.
Page 26 of 31
public final class ShapesCounter {
private static int shapesCount = 0; // total number of geometrical objects
private static final int maxCounter = 1000; // maximum number of objects
protected static int shapesCount() {
return shapesCount;
}
protected static void incrementShapesCount() {
shapesCount++;
}
protected static void decrementShapesCount() {
shapesCount--;
}
}
Shape.java
A class defining common aspects of shapes such as the coordinates of the distinguished point of the shape.
public class Shape {
protected double x, y; // position of geometrical object
}
Circle.java
A class for a circular shape with limited radius, a method to rest the maximal size, and methods to compute
the area and the circumference of the circle.
public class Circle extends Shape {
protected double r; // radius
private static double maxSize = 100; // maximal radius
Circle(double x, double y, double r) {
super.x = x;
super.y = y;
this.r = r;
ShapesCounter.incrementShapesCount();
}
public static void setMaxSize(double size) {
maxSize = size;
}
public double area() {
return MathConstants.PI * r * r;
}
public double circumference() {
return 2 * MathConstants.PI * r;
}
}
Square.java
A class for a square shape with methods to compute the area and the circumference of the square.
public class Square extends Shape {
protected double size; // radius
private static double maxSize = 100; // maximal size
Square(double x, double y, double size) {
Page 27 of 31
super.x = x;
super.y = y;
this.size = size;
ShapesCounter.incrementShapesCount();
}
public static void setMaxSize(double size) {
maxSize = size;
}
public double area() {
return size * size;
}
public double circumference() {
return 4 * size;
}
}
Nested Classes
The Java programming language allows you to define a class within another class. Such a class is called a
nested class and is illustrated here:
class OuterClass {
...
class NestedClass {
...
}
}
Terminology: Nested classes are divided into two categories: static and non-static. Nested classes that are declared
static are simply called static nested classes. Non-static nested classes are called inner classes.
class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other
members of the enclosing class, even if they are declared private. Static nested classes do not have access to
other members of the enclosing class. As a member of the OuterClass, a nested class can be declared private,
public, protected, or package private. (Recall that outer classes can only be declared public or package private.)
Why Use Nested Classes?
There are several compelling reasons for using nested classes, among them:
Page 28 of 31
 It is a way of logically grouping classes that are only used in one place.
 It increases encapsulation.
 Nested classes can lead to more readable and maintainable code.
Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it in that class
and keep the two together. Nesting such "helper classes" makes their package more streamlined.
Increased encapsulation—Consider two top-level classes, A and B, where B needs access to members of A
that would otherwise be declared private. By hiding class B within class A, A's members can be declared private
and B can access them. In addition, B itself can be hidden from the outside world.
More readable, maintainable code—Nesting small classes within top-level classes places the code closer to
where it is used.
Static Nested Classes
As with class methods and variables, a static nested class is associated with its outer class. And like static class
methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing
class — it can use them only through an object reference.
Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other
top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level
class for packaging convenience.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
Inner Classes
As with instance methods and variables, an inner class is associated with an instance of its enclosing class and
has direct access to that object's methods and fields. Also, because an inner class is associated with an
instance, it cannot define any static members itself.
Objects that are instances of an inner class exist within an instance of the outer class. Consider the following
classes:
class OuterClass {
...
class InnerClass {
...
}
}
Page 29 of 31
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods
and fields of its enclosing instance. The next figure illustrates this idea.
An Instance of InnerClass Exists Within an Instance of OuterClass
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the
outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
Additionally, there are two special kinds of inner classes: local classes and anonymous classes (also called
anonymous inner classes). Both of these will be discussed briefly in the next section.
Inner Class Example
To see an inner class in use, let's first consider an array. In the following example, we will create an array, fill it
with integer values and then output only values of even indices of the array in ascending order.
The DataStructure class below consists of:
 The DataStructure outer class, which includes methods to add an integer onto the array and print out values of
even indices of the array.
 The InnerEvenIterator inner class, which is similar to a standard Java iterator. Iterators are used to step through a
data structure and typically have methods to test for the last element, retrieve the current element, and move
to the next element.
 A main method that instantiates a DataStructure object (ds) and uses it to fill the arrayOfInts array with integer
values (0, 1, 2, 3, etc.), then calls a printEven method to print out values of even indices of arrayOfInts.
public class DataStructure {
// create an array
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
public DataStructure() {
// fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
public void printEven() {
// print out values of even indices of the array
InnerEvenIterator iterator = this.new InnerEvenIterator();
Page 30 of 31
while (iterator.hasNext()) {
System.out.println(iterator.getNext() + " ");
}
}
// inner class implements the Iterator pattern
private class InnerEvenIterator {
// start stepping through the array from the beginning
private int next = 0;
public boolean hasNext() {
// check if a current element is the last in the array
return (next <= SIZE - 1);
}
public int getNext() {
// record a value of an even index of the array
int retValue = arrayOfInts[next];
//get the next even element
next += 2;
return retValue;
}
}
public static void main(String s[]) {
// fill the array with integer values and print out only
// values of even indices
DataStructure ds = new DataStructure();
ds.printEven();
}
}
The output is:
0 2 4 6 8 10 12 14
Note that the InnerEvenIterator class refers directly to the arrayOfInts instance variable of the DataStructure object.
Inner classes can be used to implement helper classes like the one shown in the example above. If you plan on
handling user-interface events, you will need to know how to use inner classes because the event-handling
mechanism makes extensive use of them.
Local and Anonymous Inner Classes
There are two additional types of inner classes. You can declare an inner class within the body of a method.
Such a class is known as a local inner class. You can also declare an inner class within the body of a method
without naming it. These classes are known as anonymous inner classes. You will encounter such classes in
advanced Java programming.
Modifiers
You can use the same modifiers for inner classes that you use for other members of the outer class. For
example, you can use the access specifiers — private, public, and protected — to restrict access to inner
classes, just as you do to other class members.
Summary of Nested Classes
Page 31 of 31
A class defined within another class is called a nested class. Like other members of a class, a nested class can
be declared static or not. A nonstatic nested class is called an inner class. An instance of an inner class can
exist only within an instance of its enclosing class and has access to its enclosing class's members even if they
are declared private.
The following table shows the types of nested classes:
Types of Nested Classes
Type Scope Inner
static nested class member no
inner [non-static] class member yes
local class local yes
anonymous class only the point where it is defined yes

More Related Content

What's hot

C++ Constructor destructor
C++ Constructor destructorC++ Constructor destructor
C++ Constructor destructorDa Mystic Sadi
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programmingAshita Agrawal
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructorSaharsh Anand
 
Java Static Factory Methods
Java Static Factory MethodsJava Static Factory Methods
Java Static Factory MethodsYe Win
 
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsLecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsSyed Afaq Shah MACS CP
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructorsVineeta Garg
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructorsNilesh Dalvi
 
Constructor and Destructor PPT
Constructor and Destructor PPTConstructor and Destructor PPT
Constructor and Destructor PPTShubham Mondal
 
constructor and destructor
constructor and destructorconstructor and destructor
constructor and destructorVENNILAV6
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java pptkunal kishore
 
Arrays, Structures And Enums
Arrays, Structures And EnumsArrays, Structures And Enums
Arrays, Structures And EnumsBhushan Mulmule
 
An introduction to constructor
An introduction to constructorAn introduction to constructor
An introduction to constructorNiby Babu
 
Constructor and destructor in oop
Constructor and destructor in oop Constructor and destructor in oop
Constructor and destructor in oop Samad Qazi
 
Chap2 class,objects
Chap2 class,objectsChap2 class,objects
Chap2 class,objectsraksharao
 

What's hot (20)

C++ Constructor destructor
C++ Constructor destructorC++ Constructor destructor
C++ Constructor destructor
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programming
 
C# Constructors
C# ConstructorsC# Constructors
C# Constructors
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Java Static Factory Methods
Java Static Factory MethodsJava Static Factory Methods
Java Static Factory Methods
 
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsLecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Constructor and Destructor PPT
Constructor and Destructor PPTConstructor and Destructor PPT
Constructor and Destructor PPT
 
constructor and destructor
constructor and destructorconstructor and destructor
constructor and destructor
 
Constructor & Destructor
Constructor & DestructorConstructor & Destructor
Constructor & Destructor
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
 
Arrays, Structures And Enums
Arrays, Structures And EnumsArrays, Structures And Enums
Arrays, Structures And Enums
 
An introduction to constructor
An introduction to constructorAn introduction to constructor
An introduction to constructor
 
Constructor and destructor in oop
Constructor and destructor in oop Constructor and destructor in oop
Constructor and destructor in oop
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Chap2 class,objects
Chap2 class,objectsChap2 class,objects
Chap2 class,objects
 
Chap08
Chap08Chap08
Chap08
 
Classes1
Classes1Classes1
Classes1
 

Similar to Class notes(week 3) on class objects and methods

Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
 
Cis 355 i lab 3 of 6
Cis 355 i lab 3 of 6Cis 355 i lab 3 of 6
Cis 355 i lab 3 of 6helpido9
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptxRassjb
 
ConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONShweta Shah
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Jalpesh Vasa
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptxarjun431527
 
C questions
C questionsC questions
C questionsparm112
 
C++ beginner's guide ch08
C++ beginner's guide ch08C++ beginner's guide ch08
C++ beginner's guide ch08Jotham Gadot
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxchetanpatilcp783
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfSudhanshiBakre1
 
Class and Object.pptx
Class and Object.pptxClass and Object.pptx
Class and Object.pptxHailsh
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfSudhanshiBakre1
 
08review (1)
08review (1)08review (1)
08review (1)IIUM
 

Similar to Class notes(week 3) on class objects and methods (20)

Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
Intake 37 4
Intake 37 4Intake 37 4
Intake 37 4
 
Cis 355 i lab 3 of 6
Cis 355 i lab 3 of 6Cis 355 i lab 3 of 6
Cis 355 i lab 3 of 6
 
Java class
Java classJava class
Java class
 
Java getstarted
Java getstartedJava getstarted
Java getstarted
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
 
ConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTION
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
 
Lecture11.docx
Lecture11.docxLecture11.docx
Lecture11.docx
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
 
C questions
C questionsC questions
C questions
 
C++ beginner's guide ch08
C++ beginner's guide ch08C++ beginner's guide ch08
C++ beginner's guide ch08
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 
Class and Object.pptx
Class and Object.pptxClass and Object.pptx
Class and Object.pptx
 
Online CPP Homework Help
Online CPP Homework HelpOnline CPP Homework Help
Online CPP Homework Help
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 
08review (1)
08review (1)08review (1)
08review (1)
 

More from Kuntal Bhowmick

Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loopsMultiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loopsKuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...Kuntal Bhowmick
 
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)Kuntal Bhowmick
 
1. introduction to E-commerce
1. introduction to E-commerce1. introduction to E-commerce
1. introduction to E-commerceKuntal Bhowmick
 
Computer graphics question for exam solved
Computer graphics question for exam solvedComputer graphics question for exam solved
Computer graphics question for exam solvedKuntal Bhowmick
 
DBMS and Rdbms fundamental concepts
DBMS and Rdbms fundamental conceptsDBMS and Rdbms fundamental concepts
DBMS and Rdbms fundamental conceptsKuntal Bhowmick
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interviewKuntal Bhowmick
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview QuestionsKuntal Bhowmick
 
Operating system Interview Questions
Operating system Interview QuestionsOperating system Interview Questions
Operating system Interview QuestionsKuntal Bhowmick
 
Computer Network Interview Questions
Computer Network Interview QuestionsComputer Network Interview Questions
Computer Network Interview QuestionsKuntal Bhowmick
 
Distributed operating systems cs704 a class test
Distributed operating systems cs704 a class testDistributed operating systems cs704 a class test
Distributed operating systems cs704 a class testKuntal Bhowmick
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solutionKuntal Bhowmick
 

More from Kuntal Bhowmick (20)

Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loopsMultiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
 
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
 
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
 
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
 
1. introduction to E-commerce
1. introduction to E-commerce1. introduction to E-commerce
1. introduction to E-commerce
 
Computer graphics question for exam solved
Computer graphics question for exam solvedComputer graphics question for exam solved
Computer graphics question for exam solved
 
DBMS and Rdbms fundamental concepts
DBMS and Rdbms fundamental conceptsDBMS and Rdbms fundamental concepts
DBMS and Rdbms fundamental concepts
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interview
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
 
Operating system Interview Questions
Operating system Interview QuestionsOperating system Interview Questions
Operating system Interview Questions
 
Computer Network Interview Questions
Computer Network Interview QuestionsComputer Network Interview Questions
Computer Network Interview Questions
 
C interview questions
C interview  questionsC interview  questions
C interview questions
 
C question
C questionC question
C question
 
Distributed operating systems cs704 a class test
Distributed operating systems cs704 a class testDistributed operating systems cs704 a class test
Distributed operating systems cs704 a class test
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solution
 

Recently uploaded

CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitterShivangiSharma879191
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 

Recently uploaded (20)

Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 

Class notes(week 3) on class objects and methods

  • 1. Page 1 of 31 Class Notes on Class Objects and Methods (Week - 3) Contents:- Defining a class, Data fields Declaration, Creating Objects, Accessing Class Members, Constructors, Methods Overloading, access specifiers, operators, control statements & loops, array, finalize and garbage collection, this keyword, use of objects as parameter & methods returning objects, call by value & call by reference, static variables & methods, garbage collection, nested and inner classes. What Is a Class? In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created. The following Bicycle class is one possible implementation of a bicycle: class Bicycle { int cadence = 0; int speed = 0; int gear = 1; void changeCadence(int newValue) { cadence = newValue; } void changeGear(int newValue) { gear = newValue; } void speedUp(int increment) { speed = speed + increment; } void applyBrakes(int decrement) { speed = speed - decrement; } void printStates() { System.out.println("cadence:" + cadence + " speed:" + speed + " gear:" + gear); } } The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of bicycle objects. The fields cadence, speed, and gear represent the object's state, and the methods (changeCadence, changeGear, speedUp etc.) define its interaction with the outside world. You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete application; it's just the blueprint for bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects belongs to some other class in your application.
  • 2. Page 2 of 31 Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their methods: class BicycleDemo { public static void main(String[] args) { // Create two different // Bicycle objects Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle(); // Invoke methods on // those objects bike1.changeCadence(50); bike1.speedUp(10); bike1.changeGear(2); bike1.printStates(); bike2.changeCadence(50); bike2.speedUp(10); bike2.changeGear(2); bike2.changeCadence(40); bike2.speedUp(10); bike2.changeGear(3); bike2.printStates(); } } The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles: cadence:50 speed:10 gear:2 cadence:40 speed:20 gear:3 Declaring Member Variables There are several kinds of variables:  Member variables in a class—these are called fields.  Variables in a method or block of code—these are called local variables.  Variables in method declarations—these are called parameters. The Bicycle class uses the following lines of code to define its fields: public int cadence; public int gear; public int speed; Field declarations are composed of three components, in order: 1. Zero or more modifiers, such as public or private. 2. The field's type. 3. The field's name. The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int). The public keyword identifies these fields as public members, accessible by any object that can access the class.
  • 3. Page 3 of 31 Objects A typical Java program creates many objects, which as you know, interact by invoking methods. Through these object interactions, a program can carry out various tasks, such as implementing a GUI, running an animation, or sending and receiving information over a network. Once an object has completed the work for which it was created, its resources are recycled for use by other objects. The following two statements of BicycleDemo class create two separate Bicycle objects. Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle(); Creating Objects As you know, a class provides the blueprint for objects; you create an object from a class. Each of the following statements taken from the BicycleDemo program creates an object and assigns it to a variable: Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle(); The 2 line creates an object of the Bicycle class. Each of these statements has three parts (discussed in detail below): 1. Declaration: The code set in bold are all variable declarations that associate a variable name with an object type. 2. Instantiation: The new keyword is a Java operator that creates the object. 3. Initialization: The new operator is followed by a call to a constructor, which initializes the new object. Declaring a Variable to Refer to an Object Previously, you learned that to declare a variable, you write: type name; This notifies the compiler that you will use name to refer to data whose type is type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable. You can also declare a reference variable on its own line. For example: Point originOne; If you declare originOne like this, its value will be undetermined until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object. For that, you need to use the new operator, as described in the next section. You must assign an object to originOne before you use it in your code. Otherwise, you will get a compiler error.A variable in this state, which currently references no object, can be illustrated as follows (the variable name, originOne, plus a reference pointing to nothing):
  • 4. Page 4 of 31 Instantiating a Class The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor. Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the appropriate type, like: Point originOne = new Point(23, 94); Initializing an Object Here's the code for the Point class: class Point { public int x = 0; public int y = 0; //constructor Point(int a, int b) { x = a; y = b; } } This class contains a single constructor. You can recognize a constructor because its declaration uses the same name as the class and it has no return type. The constructor in the Point class takes two integer arguments, as declared by the code (int a, int b). The following statement provides 23 and 94 as values for those arguments: Point originOne = new Point(23, 94); The result of executing this statement can be illustrated in the next figure:
  • 5. Page 5 of 31 Here's the code for the Rectangle class, which contains four constructors: class Rectangle { int width = 0; int height = 0; Point origin; // four constructors Rectangle() { origin = new Point(0, 0); } Rectangle(Point p) { origin = p; } Rectangle(int w, int h) { origin = new Point(0, 0); width = w; height = h; } Rectangle(Point p, int w, int h) { origin = p; width = w; height = h; } // a method for moving the rectangle void move(int x, int y) { origin.x = x; origin.y = y; } // a method for computing the area of the rectangle int getArea() { return width * height; } } Each constructor lets you provide initial values for the rectangle's size and width, using both primitive and reference types. If a class has multiple constructors, they must have different signatures. The Java compiler differentiates the constructors based on the number and the type of the arguments. When the Java compiler encounters the following code, it knows to call the constructor in the Rectangle class that requires a Point argument followed by two integer arguments: Rectangle rectOne = new Rectangle(originOne, 100, 200); This calls one of Rectangle's constructors that initializes origin to originOne. Also, the constructor sets width to 100 and height to 200. Now there are two references to the same Point object—an object can have multiple references to it, as shown in the next figure:
  • 6. Page 6 of 31 The following line of code calls the Rectangle constructor that requires two integer arguments, which provide the initial values for width and height. If you inspect the code within the constructor, you will see that it creates a new Point object whose x and y values are initialized to 0: Rectangle rectTwo = new Rectangle(50, 100); The Rectangle constructor used in the following statement doesn't take any arguments, so it's called a no- argument constructor: Rectangle rect = new Rectangle(); All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program. Defining Methods Here is an example of a typical method declaration: public double calculateAnswer(double wingSpan, int numberOfEngines, double length, double grossTons) { //do the calculation here } The only required elements of a method declaration are the method's return type, name, a pair of parentheses, (), and a body between braces, {}. More generally, method declarations have six components, in order: 1. Modifiers—such as public, private, and others you will learn about later. 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. An exception list—to be discussed later. 6. The method body, enclosed between braces—the method's code, including the declaration of local variables, goes here. Modifiers, return types, and parameters will be discussed later in this lesson. Exceptions are discussed in a later lesson. Definition: Two of the components of a method declaration comprise the method signature—the method's name and the parameter types.
  • 7. Page 7 of 31 The signature of the method declared above is: calculateAnswer(double, int, double, double) Naming a Method Although a method name can be any legal identifier, code conventions restrict method names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized. Here are some examples:  run  runFast  getBackground  getFinalData  compareTo  setX  isEmpty Typically, a method has a unique name within its class. However, a method might have the same name as other methods due to method overloading. Overloading Methods The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled "Interfaces and Inheritance"). Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so on) and that contains a method for drawing each data type. It is cumbersome to use a new name for each method—for example, drawString, drawInteger, drawFloat, and so on. In the Java programming language, you can use the same name for all the drawing methods but pass a different argument list to each method. Thus, the data drawing class might declare four methods named draw, each of which has a different parameter list. public class DataArtist { ... public void draw(String s) { ... } public void draw(int i) { ... } public void draw(double f) { ... } public void draw(int i, double f) { ... } }
  • 8. Page 8 of 31 Overloaded methods are differentiated by the number and the type of the arguments passed into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require different argument types. You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart. The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type. Note: Overloaded methods should be used sparingly, as they can make code much less readable. Constructors A constructor is a special method that is used to initialize a newly created objectand is called just after the memory is allocated for the objectIt can be used to initialize the objects ,to required ,or default valuesat the time of object creationIt is not mandatory for the coder to write a constructor for the class If no user defined constructor is provided for a class, compiler initializes member variables to its default values.  numeric data types are set to 0  char data types are set to null character(‘’)  reference variables are set to null In order to create a Constructor observe the following rules 1. It has the same name as the class 2. It should not return a value not even void class Demo{ int value1; int value2; Demo(){ value1 = 10; value2 = 20; System.out.println("Inside Constructor"); } public void display(){ System.out.println("Value1 === "+value1); System.out.println("Value2 === "+value2); } public static void main(String args[]){ Demo d1 = new Demo(); d1.display(); } }
  • 9. Page 9 of 31 Step 2) Save , Run & Compile the code. Observe the output. constructor overloading Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists. The compiler differentiates these constructors by taking into account the number of parameters in the list and their type Examples of valid constructors for class Account are  Account(int a);  Account (int a,int b);  Account (String a,int b); class Demo{ int value1; int value2; /*Demo(){ value1 = 10; value2 = 20; System.out.println("Inside 1st Constructor"); }*/ Demo(int a){ value1 = a; System.out.println("Inside 2nd Constructor"); } Demo(int a,int b){ value1 = a; value2 = b; System.out.println("Inside 3rd Constructor"); } public void display(){ System.out.println("Value1 === "+value1); System.out.println("Value2 === "+value2); } public static void main(String args[]){ Demo d1 = new Demo(); Demo d2 = new Demo(30); Demo d3 = new Demo(30,40); d1.display(); d2.display(); d3.display(); } } Every class has a default Constructor. Default Constructor for class Demo is Demo(). In case you do not provide this constructor the compiler creates it for you and initializes the variables to default values. You may choose to override this default constructor and initialize variables to your desired values .But if you specify a parametrized constructor like Demo(int a) ,and want to use the default constructor Demo(), it is mandatory for you to specify it. In other words, in case your Constructor is overridden , and you want to use the default constructor , its need to be specified. Access Specifiers
  • 10. Page 10 of 31 One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. In this way the chance of making accidental mistakes in changing values is minimized. Java allows you to control access to classes, methods, and fields via so-called access specifiers. Java offers four access specifiers, listed below in decreasing accessibility:  public  protected  default (no specifier)  private We look at these access specifiers in more detail. public public classes, methods, and fields can be accessed from everywhere. The only constraint is that a file with Java source code can only contain one public class whose name must also match with the filename. If it exists, this public class represents the application or the applet, in which case the public keyword is necessary to enable your Web browser or appletviewer to show the applet. You use public classes, methods, or fields only if you explicitly want to offer access to these entities and if this access cannot do any harm. An example of a square determined by the position of its upper-left corner and its size: public class Square { // public class public x, y, size; // public instance variables } protected protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package, but not from anywhere else. You use the protected access level when it is appropriate for a class's subclasses to have access to the method or field, but not for unrelated classes. default (no specifier) If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package. This access-level is convenient if you are creating packages. For example, a geometry package that contains Square and Tiling classes, may be easier and cleaner to implement if the coordinates of the upper-left corner of a Square are directly available to the Tiling class but not outside the geometry package. private private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. So, the private access specifier is opposite to the public access specifier. It is mostly used for encapsulation: data are hidden within the class and accessor methods are provided. An example, in which the position of the upper-left corner of a square can be set or obtained by accessor methods, but individual coordinates are not accessible to the user.
  • 11. Page 11 of 31 public class Square { // public class private double x, y // private (encapsulated) instance variables public setCorner(int x, int y) { // setting values of private fields this.x = x; this.y = y; } public getCorner() { // setting values of private fields return Point(x, y); } } Summary of Access Specifiers The following table summarizes the access level permitted by each specifier. Situation public protected default private Accessible to class from same package? yes yes yes no Accessible to class from different package? yes no, unless it is a subclass no no Note the difference between the default access which is in fact more restricted than the protected access. Without access specifier (the default choice), methods and variables are accessible only within the class that defines them and within classes that are part of the same package. They are not visible to subclasses unless these are in the same package. protected methods and variables are visible to subclasses regardless of which package they are in. Java Control Flow Statements Java Control statements control the order of execution in a java program, based on data values and conditional logic. There are three main categories of control flow statements;  Selection statements: if, if-else and switch.  Loop statements: while, do-while and for.  Transfer statements: break, continue. We use control statements when we want to change the default sequential order of execution Selection Statements - The If Statement The if statement executes a block of code only if the specified expression is true. If the value is false, then the if block is skipped and execution continues with the rest of the program. You can either have a single statement or a block of code within an if statement. Note that the conditional expression must be a Boolean expression. The simple if statement has the following syntax: if (<conditional expression>) <statement action> Below is an example that demonstrates conditional execution based on if statement condition.
  • 12. Page 12 of 31 public class IfStatementDemo { public static void main(String[] args) { int a = 10, b = 20; if (a > b) System.out.println("a > b"); if (a < b) System.out.println("b > a"); } } Output b > a The If-else Statement The if/else statement is an extension of the if statement. If the statements in the if statement fails, the statements in the else block are executed. You can either have a single statement or a block of code within if- else blocks. Note that the conditional expression must be a Boolean expression. The if-else statement has the following syntax: if (<conditional expression>) <statement action> else <statement action> Below is an example that demonstrates conditional execution based on if else statement condition. public class IfElseStatementDemo { public static void main(String[] args) { int a = 10, b = 20; if (a > b) { System.out.println("a > b"); } else { System.out.println("b > a"); } } } Output b > a Switch Case Statement The switch case statement, also called a case statement is a multi-way branch with several choices. A switch is easier to implement than a series of if/else statements. The switch statement begins with a keyword, followed by an expression that equates to a no long integral value. Following the controlling expression is a code block that contains zero or more labeled cases. Each label must equate to an integer constant and each must be unique. When the switch statement executes, it compares the value of the controlling expression to the values
  • 13. Page 13 of 31 of each case label. The program will select the value of the case label that equals the value of the controlling expression and branch down that path to the end of the code block. If none of the case label values match, then none of the codes within the switch statement code block will be executed. Java includes a default label to use in cases where there are no matches. We can have a nested switch within a case block of an outer switch. Its general form is as follows: switch (<non-long integral expression>) { case label1: <statement1> case label2: <statement2> … case labeln: <statementn> default: <statement> } // end switch When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit in the middle of the switch statement code block, you must insert a break statement, which causes the program to continue executing after the current code block. Below is a java example that demonstrates conditional execution based on nested if else statement condition to find the greatest of 3 numbers. public class SwitchCaseStatementDemo { public static void main(String[] args) { int a = 10, b = 20, c = 30; int status = -1; if (a > b && a > c) { status = 1; } else if (b > c) { status = 2; } else { status = 3; } switch (status) { case 1: System.out.println("a is the greatest"); break; case 2: System.out.println("b is the greatest"); break; case 3: System.out.println("c is the greatest"); break; default: System.out.println("Cannot be determined"); } } } Output c is the greatest
  • 14. Page 14 of 31 Iteration Statements - While Statement The while statement is a looping construct control statement that executes a block of code while a condition is true. You can either have a single statement or a block of code within the while loop. The loop will never be executed if the testing expression evaluates to false. The loop condition must be a boolean expression. The syntax of the while loop is while (<loop condition>) <statements> Below is an example that demonstrates the looping construct namely while loop used to print numbers from 1 to 10. public class WhileLoopDemo { public static void main(String[] args) { int count = 1; System.out.println("Printing Numbers from 1 to 10"); while (count <= 10) { System.out.println(count++); } } } Output Printing Numbers from 1 to 10 1 2 3 4 5 6 7 8 9 10 Do-while Loop Statement The do-while loop is similar to the while loop, except that the test is performed at the end of the loop instead of at the beginning. This ensures that the loop will be executed at least once. A do-while loop begins with the keyword do, followed by the statements that make up the body of the loop. Finally, the keyword while and the test expression completes the do-while loop. When the loop condition becomes false, the loop is terminated and execution continues with the statement immediately following the loop. You can either have a single statement or a block of code within the do-while loop. The syntax of the do-while loop is
  • 15. Page 15 of 31 do <loop body> while (<loop condition>); Below is an example that demonstrates the looping construct namely do-while loop used to print numbers from 1 to 10. public class DoWhileLoopDemo { public static void main(String[] args) { int count = 1; System.out.println("Printing Numbers from 1 to 10"); do { System.out.println(count++); } while (count <= 10); } } Output Printing Numbers from 1 to 10 1 2 3 4 5 6 7 8 9 10 Below is an example that creates A Fibonacci sequence controlled by a do-while loop public class Fibonacci { public static void main(String args[]) { System.out.println("Printing Limited set of Fibonacci Sequence"); double fib1 = 0; double fib2 = 1; double temp = 0; System.out.println(fib1); System.out.println(fib2); do { temp = fib1 + fib2; System.out.println(temp); fib1 = fib2; //Replace 2nd with first number fib2 = temp; //Replace temp number with 2nd number } while (fib2 < 5000); } } Output Printing Limited set of Fibonacci Sequence
  • 16. Page 16 of 31 0.0 1.0 1.0 2.0 3.0 5.0 8.0 13.0 21.0 34.0 55.0 89.0 144.0 233.0 377.0 610.0 987.0 1597.0 2584.0 4181.0 6765.0 For Loops The for loop is a looping construct which can execute a set of instructions a specified number of times. It’s a counter controlled loop. The syntax of the loop is as follows: for (<initialization>; <loop condition>; <increment expression>) <loop body> The first part of a for statement is a starting initialization, which executes once before the loop begins. The <initialization> section can also be a comma-separated list of expression statements. The second part of a for statement is a test expression. As long as the expression is true, the loop will continue. If this expression is evaluated as false the first time, the loop will never be executed. The third part of the for statement is the body of the loop. These are the instructions that are repeated each time the program executes the loop. The final part of the for statement is an increment expression that automatically executes after each repetition of the loop body. Typically, this statement changes the value of the counter, which is then tested to see if the loop should continue. All the sections in the for-header are optional. Any one of them can be left empty, but the two semicolons are mandatory. In particular, leaving out the <loop condition> signifies that the loop condition is true. The (;;) form of for loop is commonly used to construct an infinite loop. Below is an example that demonstrates the looping construct namely for loop used to print numbers from 1 to 10. public class ForLoopDemo { public static void main(String[] args) { System.out.println("Printing Numbers from 1 to 10");
  • 17. Page 17 of 31 for (int count = 1; count <= 10; count++) { System.out.println(count); } } } Output Printing Numbers from 1 to 10 1 2 3 4 5 6 7 8 9 10 Transfer Statements - Continue Statement A continue statement stops the iteration of a loop (while, do or for) and causes execution to resume at the top of the nearest enclosing loop. You use a continue statement when you do not want to execute the remaining statements in the loop, but you do not want to exit the loop itself. The syntax of the continue statement is continue; // the unlabeled form continue <label>; // the labeled form You can also provide a loop with a label and then use the label in your continue statement. The label name is optional, and is usually only used when you wish to return to the outermost loop in a series of nested loops. Below is a program to demonstrate the use of continue statement to print Odd Numbers between 1 to 10. public class ContinueExample { public static void main(String[] args) { System.out.println("Odd Numbers"); for (int i = 1; i <= 10; ++i) { if (i % 2 == 0) continue; // Rest of loop body skipped when i is even System.out.println(i + "t"); } } } Output Odd Numbers 1
  • 18. Page 18 of 31 3 5 7 9 Break Statement The break statement transfers control out of the enclosing loop ( for, while, do or switch statement). You use a break statement when you want to jump immediately to the statement following the enclosing control structure. You can also provide a loop with a label, and then use the label in your break statement. The label name is optional, and is usually only used when you wish to terminate the outermost loop in a series of nested loops. The Syntax for break statement is as shown below; break; // the unlabeled form break <label>; // the labeled form Below is a program to demonstrate the use of break statement to print numbers Numbers 1 to 10. public class BreakExample { public static void main(String[] args) { System.out.println("Numbers 1 - 10"); for (int i = 1;; ++i) { if (i == 11) break; // Rest of loop body skipped when i is even System.out.println(i + "t"); } } } Output Numbers 1 – 10 1 2 3 4 5 6 7 8 9 10 finalize method finalize method in java is a special method much like main method in java. finalize() is called before Garbage collector reclaim the Object, its last chance for any object to perform cleanup activity i.e. releasing any system resources held, closing connection if open etc. Main issue with finalize method in java is its not guaranteed by
  • 19. Page 19 of 31 JLS that it will be called by Garbage collector or exactly when it will be called, for example an object may wait indefinitely after becoming eligible for garbage collection and before its finalize() method gets called. similarly even after finalize gets called its not guaranteed it will be immediately collected. Because of above reason it make no sense to use finalize method for releasing critical resources or perform any time critical activity inside finalize. It may work in development in one JVM but may not work in other JVM. In this java tutorial we will see some important points about finalize method in Java, How to use finalize method, what to do and what not to do inside finalize in Java. Garbage Collection The Java virtual machine's heap stores all objects created by a running Java application. Objects are created by the new, newarray, anewarray, and multianewarray instructions, but never freed explicitly by the code. Garbage collection is the process of automatically freeing objects that are no longer referenced by the program. This chapter does not describe an official Java garbage-collected heap, because none exists. As mentioned in earlier chapters, the Java virtual machine specification does not require any particular garbage collection technique. It doesn't even require garbage collection at all. But until infinite memory is invented, most Java virtual machine implementations will likely come with garbage-collected heaps. This chapter describes various garbage collection techniques and explains how garbage collection works in Java virtual machines. Accompanying this chapter on the CD-ROM is an applet that interactively illustrates the material presented in the chapter. The applet, named Heap of Fish, simulates a garbage-collected heap in a Java virtual machine. The simulation--which demonstrates a compacting, mark-and-sweep collector--allows you to interact with the heap as if you were a Java program: you can allocate objects and assign references to variables. The simulation also allows you to interact with the heap as if you were the Java virtual machine: you can drive the processes of garbage collection and heap compaction. At the end of this chapter, you will find a description of this applet and instructions on how to use it. Why Garbage Collection? The name "garbage collection" implies that objects no longer needed by the program are "garbage" and can be thrown away. A more accurate and up-to-date metaphor might be "memory recycling." When an object is no longer referenced by the program, the heap space it occupies can be recycled so that the space is made available for subsequent new objects. The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must run any finalizers of objects being freed. In addition to freeing unreferenced objects, a garbage collector may also combat heap fragmentation. Heap fragmentation occurs through the course of normal program execution. New objects are allocated, and unreferenced objects are freed such that free portions of heap memory are left in between portions occupied by live objects. Requests to allocate new objects may have to be filled by extending the size of the heap even though there is enough total unused space in the existing heap. This will happen if there is not enough contiguous free heap space available into which the new object will fit. On a virtual memory system, the extra paging (or swapping) required to service an ever growing heap can degrade the performance of the executing program. On an embedded system with low memory, fragmentation could cause the virtual machine to "run out of memory" unnecessarily.
  • 20. Page 20 of 31 Garbage collection relieves you from the burden of freeing allocated memory. Knowing when to explicitly free allocated memory can be very tricky. Giving this job to the Java virtual machine has several advantages. First, it can make you more productive. When programming in non-garbage-collected languages you can spend many late hours (or days or weeks) chasing down an elusive memory problem. When programming in Java you can use that time more advantageously by getting ahead of schedule or simply going home to have a life. A second advantage of garbage collection is that it helps ensure program integrity. Garbage collection is an important part of Java's security strategy. Java programmers are unable to accidentally (or purposely) crash the Java virtual machine by incorrectly freeing memory. A potential disadvantage of a garbage-collected heap is that it adds an overhead that can affect program performance. The Java virtual machine has to keep track of which objects are being referenced by the executing program, and finalize and free unreferenced objects on the fly. This activity will likely require more CPU time than would have been required if the program explicitly freed unnecessary memory. In addition, programmers in a garbage-collected environment have less control over the scheduling of CPU time devoted to freeing objects that are no longer needed. this keyword Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this 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. You can use this anywhere a reference to an object of the current class' type is permitted. To better understand what this refers to, consider the following version of Box( ): // A redundant use of this. Box(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; } 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, one of which is explained in the next section. Instance Variable Hiding As you know, 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. However, when a local variable has the same name as an instance variable, the local variable hides the instance variable. This is why width, height, and depth were not used as the names of the parameters to the Box( ) constructor inside the Box class. If they had been, then width would have referred to the formal parameter, hiding the instance variable width. While it is usually easier to simply use different names, there is another way around this situation. Because this lets you refer directly to the object, you can use it to resolve any name space collisions that might occur between instance variables and local variables. 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:
  • 21. Page 21 of 31 // Use this to resolve name-space collisions. Box(double width, double height, double depth) { this.width = width; this.height = height; this.depth = depth; } A word of caution: The use of this in such a context can sometimes be confusing, and some programmers are careful not to use local variables and formal parameter names that hide instance variables. Of course, other programmers believe the contrary—that it is a good convention to use the same names for clarity, and use this to overcome the instance variable hiding. It is a matter of taste which approach you adopt. Although this is of no significant value in the examples just shown, it is very useful in certain situations. This is an extract from the book: Java 2 - The Complete Reference by Herbert Schildt. Using Objects as Parameters So far we have only been using simple types as parameters to methods. However, it is both correct and common to pass objects to methods. For example, consider the following short program: // 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; } } 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)); } } This program generates the following output: ob1 == ob2: true ob1 == ob3: false As you can see, 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. Notice that the parameter o in equals( ) specifies Test as its
  • 22. Page 22 of 31 type. Although Test is a class type created by the program, it is used in just the same way as Java’s built-in types. One of the most common uses of object parameters involves constructors. Frequently you will want to construct a new object so that it is initially the same as some existing object. To do this, you must define a constructor that takes an object of its class as a parameter. For example, the following version of Box allows one object to initialize another: // 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; } // 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; } } 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; // get volume of first box vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); // get volume of cube
  • 23. Page 23 of 31 vol = mycube.volume(); System.out.println("Volume of cube is " + vol); // get volume of clone vol = myclone.volume(); System.out.println("Volume of clone is " + vol); } } As you will see when you begin to create your own classes, providing many forms of constructor methods is usually required to allow objects to be constructed in a convenient and efficient manner. Can a java method return an object? Why constructors don’t have a return type? Absolutely. Make sure the method is labeled as returning an object i.e public Object objectMethod(...){ ... return (theObject); } Constructors don't have a return type because they simply "construct" an object. In that sense, they are already returning an object. Constructors implicitly returns an object, they don’t have any return type not even void. Call by Value and Call by Reference in Java There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value. The changes being done in the called method, is not affected in the calling method. In case of call by value original value is not changed. Let's take a simple example: 1. class Operation{ 2. int data=50; 3. 4. void change(int data){ 5. data=data+100;//changes will be in the local variable only 6. } 7. 8. 9. public static void main(String args[]){ 10. Operation op=new Operation(); 11. 12. System.out.println("before change "+op.data); 13. op.change(500); 14. System.out.println("after change "+op.data); 15. 16. } 17. } Output:before change 50 after change 50
  • 24. Page 24 of 31 Another Example of call by value in java In case of call by reference original value is changed if we made changes in the called method. If we pass object in place of any primitive value, original value will be changed. In this example we are passing object as a value. Let's take a simple example: 1. class Operation2{ 2. int data=50; 3. 4. void change(Operation op){ 5. op.data=op.data+100;//changes will be in the instance variable 6. } 7. 8. 9. public static void main(String args[]){ 10. Operation2 op=new Operation2(); 11. 12. System.out.println("before change "+op.data); 13. op.change(op);//passing object 14. System.out.println("after change "+op.data); 15. 16. } 17. } Output:before change 50 after change 150 Modifiers: final and static A number of modifier keywords can be placed in declarations of methods and variables, and sometimes in declarations of classes, to provide extra information or restriction on the methods or variables. Here we shall only discuss the final and static keywords.  The final Modifier  The static Modifier  The Geometrical Shapes Example The final Modifier The final modifier keyword makes that the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method. We look at these three cases in more detail. final Classes A final class cannot have subclasses. An example: public final class MathConstants { ... } This skeleton defines a class called MathConstants that is publicly accessible but cannot be subclassed. final Variables A final variable cannot be changed once it is initialized, In the above class of mathematical constants you can for example define a numerical approximation of pi by public final static double PI = 3.141592654;
  • 25. Page 25 of 31 It is a convention, but not obligatory, to capitalize the name of a final object. final Methods A final method cannot be overridden by subclasses. There are two reasons for introducing such a method: 1. Disallowing subclasses to change the meaning of the method; 2. Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code. In the class of mathematical constants you could define a final method to generate a random constant. public final static randomNumber() { ... } The static Modifier A variable or method that is shared by all instances of a class is called a class variable or class method. You recognize such a variable in Java by the static keyword in the declaration. A class variable will instantiate only one copy of the variable for the whole class instead of a separate copy for each instance of a class. A class variable belongs to a class, not to an instance of the class. You can refer to a class variable either through an instance of the class (like a normal instance variable) or through the full class name of the form classname.variable. A class method can be referred to through an instance of the class (like a normal method) or through the full class name of the form classname.method. In fact, a class is an object of the special class Class, so this naming system is consistent. You can look at the examples above for how to use class variables and class methods. You can also look at the example worked out below. The Geometrical Shapes Example We shall give an example of the Shape class with the subclasses Circle and Square. In this example you can practice your knowledge of modifiers and access specifiers. MathConstants.java A class for mathematical constants that cannot be subclassed and contains the mathematical constant pi. public final class MathConstants { public final static double PI = 3.141592654; // constant pi } ShapeCounter.java A class for counting the number of geometrical objects that cannot be subclassed and does not allow direct access to the variable that holds in fact the number of shapes; instead, accessor methods are provided to classes in the same package to which this class belongs.
  • 26. Page 26 of 31 public final class ShapesCounter { private static int shapesCount = 0; // total number of geometrical objects private static final int maxCounter = 1000; // maximum number of objects protected static int shapesCount() { return shapesCount; } protected static void incrementShapesCount() { shapesCount++; } protected static void decrementShapesCount() { shapesCount--; } } Shape.java A class defining common aspects of shapes such as the coordinates of the distinguished point of the shape. public class Shape { protected double x, y; // position of geometrical object } Circle.java A class for a circular shape with limited radius, a method to rest the maximal size, and methods to compute the area and the circumference of the circle. public class Circle extends Shape { protected double r; // radius private static double maxSize = 100; // maximal radius Circle(double x, double y, double r) { super.x = x; super.y = y; this.r = r; ShapesCounter.incrementShapesCount(); } public static void setMaxSize(double size) { maxSize = size; } public double area() { return MathConstants.PI * r * r; } public double circumference() { return 2 * MathConstants.PI * r; } } Square.java A class for a square shape with methods to compute the area and the circumference of the square. public class Square extends Shape { protected double size; // radius private static double maxSize = 100; // maximal size Square(double x, double y, double size) {
  • 27. Page 27 of 31 super.x = x; super.y = y; this.size = size; ShapesCounter.incrementShapesCount(); } public static void setMaxSize(double size) { maxSize = size; } public double area() { return size * size; } public double circumference() { return 4 * size; } } Nested Classes The Java programming language allows you to define a class within another class. Such a class is called a nested class and is illustrated here: class OuterClass { ... class NestedClass { ... } } Terminology: Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes. class OuterClass { ... static class StaticNestedClass { ... } class InnerClass { ... } } A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass, a nested class can be declared private, public, protected, or package private. (Recall that outer classes can only be declared public or package private.) Why Use Nested Classes? There are several compelling reasons for using nested classes, among them:
  • 28. Page 28 of 31  It is a way of logically grouping classes that are only used in one place.  It increases encapsulation.  Nested classes can lead to more readable and maintainable code. Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined. Increased encapsulation—Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world. More readable, maintainable code—Nesting small classes within top-level classes places the code closer to where it is used. Static Nested Classes As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference. Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience. Static nested classes are accessed using the enclosing class name: OuterClass.StaticNestedClass For example, to create an object for the static nested class, use this syntax: OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass(); Inner Classes As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself. Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes: class OuterClass { ... class InnerClass { ... } }
  • 29. Page 29 of 31 An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. The next figure illustrates this idea. An Instance of InnerClass Exists Within an Instance of OuterClass To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass.InnerClass innerObject = outerObject.new InnerClass(); Additionally, there are two special kinds of inner classes: local classes and anonymous classes (also called anonymous inner classes). Both of these will be discussed briefly in the next section. Inner Class Example To see an inner class in use, let's first consider an array. In the following example, we will create an array, fill it with integer values and then output only values of even indices of the array in ascending order. The DataStructure class below consists of:  The DataStructure outer class, which includes methods to add an integer onto the array and print out values of even indices of the array.  The InnerEvenIterator inner class, which is similar to a standard Java iterator. Iterators are used to step through a data structure and typically have methods to test for the last element, retrieve the current element, and move to the next element.  A main method that instantiates a DataStructure object (ds) and uses it to fill the arrayOfInts array with integer values (0, 1, 2, 3, etc.), then calls a printEven method to print out values of even indices of arrayOfInts. public class DataStructure { // create an array private final static int SIZE = 15; private int[] arrayOfInts = new int[SIZE]; public DataStructure() { // fill the array with ascending integer values for (int i = 0; i < SIZE; i++) { arrayOfInts[i] = i; } } public void printEven() { // print out values of even indices of the array InnerEvenIterator iterator = this.new InnerEvenIterator();
  • 30. Page 30 of 31 while (iterator.hasNext()) { System.out.println(iterator.getNext() + " "); } } // inner class implements the Iterator pattern private class InnerEvenIterator { // start stepping through the array from the beginning private int next = 0; public boolean hasNext() { // check if a current element is the last in the array return (next <= SIZE - 1); } public int getNext() { // record a value of an even index of the array int retValue = arrayOfInts[next]; //get the next even element next += 2; return retValue; } } public static void main(String s[]) { // fill the array with integer values and print out only // values of even indices DataStructure ds = new DataStructure(); ds.printEven(); } } The output is: 0 2 4 6 8 10 12 14 Note that the InnerEvenIterator class refers directly to the arrayOfInts instance variable of the DataStructure object. Inner classes can be used to implement helper classes like the one shown in the example above. If you plan on handling user-interface events, you will need to know how to use inner classes because the event-handling mechanism makes extensive use of them. Local and Anonymous Inner Classes There are two additional types of inner classes. You can declare an inner class within the body of a method. Such a class is known as a local inner class. You can also declare an inner class within the body of a method without naming it. These classes are known as anonymous inner classes. You will encounter such classes in advanced Java programming. Modifiers You can use the same modifiers for inner classes that you use for other members of the outer class. For example, you can use the access specifiers — private, public, and protected — to restrict access to inner classes, just as you do to other class members. Summary of Nested Classes
  • 31. Page 31 of 31 A class defined within another class is called a nested class. Like other members of a class, a nested class can be declared static or not. A nonstatic nested class is called an inner class. An instance of an inner class can exist only within an instance of its enclosing class and has access to its enclosing class's members even if they are declared private. The following table shows the types of nested classes: Types of Nested Classes Type Scope Inner static nested class member no inner [non-static] class member yes local class local yes anonymous class only the point where it is defined yes