java module2
java module2
Module 2 The data, or variables, defined within a class are called instance variables. The
code is contained within methods. Collectively, the methods and variables
Introducing Classes: Class Fundamentals, Declaring Objects, Assigning defined within a class are called members of the class.
Object Reference Variables, Introducing Methods, Constructors, The this A Simple Class:
Keyword, Garbage Collection.
Methods and Classes: Overloading Methods, Objects as Parameters,
Argument Passing, Returning Objects, Recursion, Access Control,
Understanding static, Introducing final, Introducing Nested and Inner
Classes.
Chapter 6, 7
Chapter 6- Introducing Classes
As stated, a class defines a new type of data. In this case, the new data type
is called Box. You will use this name to declare objects of type Box.
he most important thing to understand about a class is that it defines a new
data type. Thus, a class is a template for an object, and an object is an instance
of a class.
A class is declared by use of the class keyword. x. A simplified general form
of a class definition is shown here:
As mentioned earlier, each time you create an instance of a class, you are
creating an object that contains its own copy of each instance variable defined
by the class.
Thus, every Box object will contain its own copies of the instance variables
width, height, and depth.
To access these variables, you will use the dot (.) operator. The dot operator
links the name of the object with the name of an instance variable. For
example, to assign the width variable of mybox the value 100, you would use
the following statement mybox.width=100;
Declaring Objects
As just explained, when you create a class, you are creating a new data type.
You can use this type to declare objects of that type. First, you must declare a
variable of the class type. Second, you must acquire an actual, physical copy
of the object and assign it to that variable. You can do this using the new
operator. The new operator dynamically allocates memory for an object and
returns a reference to it. Let’s look at the details of this procedure. In the
preceding sample programs, a line similar to the following is used to declare
an object of type Box:
Box mybox = new Box();
This statement combines the two steps just described. It can be rewritten like
this to show each step more clearly:
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
Introducing Methods
Classes usually consist of two things: instance variables and methods.
Returning a Value
While the implementation of volume ( ) does move the computation of a box’s
volume inside the Box class where it belongs, it is not the best way to do it.
For example, what if another part of your program wanted to know the volume
of a box, but not display its value? A better way to implement volume ( ) is to
have it compute the volume of the box and return the result to the caller. The
following example, an improved version of the preceding program, does just
that.
Here is an example:
int x, y;
x = square(5); // x equals 25
x = square(9); // x equals 81
y = 2;
x = square(y); // x equals 4
Constructors
It can be tedious to initialize all of the variables in a class each time an instance
is created. Java allows objects to initialize themselves when they are created.
This automatic initialization is performed through the use of a constructor.
A constructor initializes an object immediately upon creation. It has the same
name as the class in which it resides and is syntactically similar to a method.
Once defined, the constructor is automatically called when the object is
created, before the new operator completes. Constructors have no return type,
not even void.
Parameterized Constructors
While the Box( ) constructor in the preceding example does initialize a Box object, it is not
very useful—all boxes have the same dimensions. What is needed is a way to construct
Box objects of various dimensions. The easy solution is to add parameters to the
constructor. For example, the following version of Box defines a parameterized constructor
that sets the dimensions of a box as specified by those parameters. Pay special attention to
how Box objects are created.
Because this lets you refer directly to the object, you can use it to resolve any
namespace 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:
Overloading Methods
In Java, it is possible to define two or more methods within the same class that
share the same name, as long as their parameter declarations are different.
When this is the case, the methods are said to be overloaded, and the process
is referred to as method overloading. Method overloading is one of the ways
that Java supports polymorphism.
When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method
to actually call. Thus, overloaded methods must differ in the type and/or
number of their parameters.
As you can see, test () is overloaded four times. The first version takes
no parameters, the second takes one integer parameter, the third takes
two integer parameters, and the fourth takes one double parameter. The
fact that the fourth version of test( ) also returns a value is of no
consequence relative to overloading, since return types do not play a role
in overload resolution.
Method overloading supports polymorphism because it is one way that
Java implements the “one interface, multiple methods” paradigm.
Overloading Constructors
In addition to overloading normal methods, you can also overload
constructor methods. To understand why, let’s return to the Box class
developed in the preceding chapter. Following is the latest version of
Box:
width= w;
class Box { height= h;
double width; depth= d;
double height;
double depth; }
} }
As you can see, the Box( ) constructor requires three parameters. This // compute and return
volume double volume() {
means that all declarations of Box objects must pass three arguments to
return width* height* depth;
the Box( ) constructor. For example, the following statement is currently
invalid:
Box ob = new Box(); }
Since Box( ) requires three arguments, it’s an error to call it without them. }
This raises some important questions. What if you simply wanted a box
class OverloadCons {
and did not care (or know) what its initial dimensions were? Or, what if public static void main(String[) args) {
you want to be able to initialize a cube by specifying only one value that // create boxes using the various
would be used for all three dimensions? As the Box class is currently constructors Box myboxl = new Box(l0, 20,
written, these other options are not available to you. 15);
Box mybox2 = new Box();
* Here, Box defines three constructors to initialize Box mycube = new
the dimensions of a box various ways. Box(?);
*/
double vol;
class Box { double
width; double // get volume of first box
height; double vol = myboxl.volume();
depth;
System.out.println("Volume of myboxl is" + vol)
// constructor used when all dimensions specified
// get volume of second
Box(double w, double h, doubled) { box vol = mybox2.volume()
;
System.out.println("Volumeof mybox2 is II
+ vol)
Canara Engineering College Page 15 Canara Engineering College Page 16
OBJECT ORIENTED PROGRAMMING WITH JAVA (BCS306A) OBJECT ORIENTED PROGRAMMING WITH JAVA (BCS306A)
// get volume of cube As you can see, the equalTo( ) method inside Test compares two objects
vol = for equality and returns the result. That is, it compares the invoking
mycube.volume( ;) object with the one that it is passed. If they contain the same values, then
System.out.println("Volumeof mycube is II
+ vol)
}
the method returns true. Otherwise, it returns false. Notice that the
} parameter o in equalTo( ) specifies Test as its type. Although Test is a
class type created by the program, it is used in just the same way as Java’s
Using Objects as Parameters built-in types.
// Objects are passed through their references.
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 class Test {
example, consider the following short program: int a, b;
} }
}
// return true if o is equal to the invoking object
class PassObjRef {
boolean equalTo(Test o) {
public static void main(String[] args) {
if(o .a == a && o . b == b ) return true; Test ob= new Test(lS, 20);
else return false;
System.out.println(11ob.a and ob.b before call: 11
+
} ob.a + " " + ob.b);
}
ob.meth(ob);
class PassOb {
public static void main(String[) args) System.out.println(11ob.a and ob.b after call: 11
+
{ Test obl = new Test(l00, 22); ob.a + " 11 + ob.b);
Test ob2 = new Test(l00, 22); }
Test ob3 = new Test(-1, -1) ; }
Sys tem .ou t.prin tln( "obl -- ob2: " +
obl.equa1To(ob2)) System.out.println("obl -- ob3: This program generates the following output:
ob.a and ob.b before call: 15 20
" + obl.equa1To(ob3 )) ob.a and ob.b after call: 30 10
}
}
Canara Engineering College Page 17 Canara Engineering College Page 18
OBJECT ORIENTED PROGRAMMING WITH JAVA (BCS306A) OBJECT ORIENTED PROGRAMMING WITH JAVA (BCS306A)
Returning Objects
A method can return any type of data, including class types that you
create. For example, in the following program, the incrByTen( ) method
returns an object in which the value of a is ten greater than it is in the
invoking object.
The
/ Returning an object .
class Test {
int a;
Test(int i) {
a= i;
Test incrByTen() {
Test temp = new Test(a+l0);
return temp;
}
}
class RetOb {
public static void main(String[l args) {
Test obl = new Test(2);
Test ob2;
ob2 = obl.incrByTen();
System.out.println("obl.a: " + obl.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob.2a after second
increase:
+ ob2.a);
}
}
[8] 8
[9] 9
// This is not OK and will cause an error
II ob.c = 100; II Error!
Introducing Access Control
As you know, encapsulation links data with the code that manipulates it. // You must access c through its methods
ob.setc(l00) ; II OK
However, encapsulation provides another important attribute: access
System.out.println("a, b, and c: " + ob.a + " " +
Control Java’s access modifiers are public, private, and protected. Java ob.b + " " + ob.getc());
also defines a default access level. protected applies only when
inheritance is involved. The other access modifiers are described next.
}
Let’s begin by defining public and private. When a member of a class
}
is modified by public, then that member can be accessed by any other
code.
As you can see, inside the Test class, a uses default access, which for
When a member of a class is specified as private, then that member can
this example is the same as specifying public. b is explicitly specified as
only be accessed by other members of its class. Now you can understand
public.
why main( ) has always been preceded by the public modifier. It is called
Member c is given private access. This means that it cannot be accessed
by code that is outside the program
by code outside of its class. So, inside the AccessTest class, c cannot be
* This program demonstrates the difference between used directly. It must be accessed through its public methods: setc( ) and
public and private. getc( ). If you were to remove the comment symbol from the beginning
of the following line,
I
class Test { / This class defines an integer stack that can hold 10
value
int a; // default access class Stack {
public int b; // public access
private int c; // private access /* Now, both stck and tos are privat.
e This means
// methods to access c
that they cannot be accidentally or
void setc(int i) { // set e's value maliciously altered in a way that would be
C = i; harmful to the stack.
*/
}
int getc() { // get e's value
private int[) stck = new
return c; int[l0); private int tos;
} // Initialize top-of-
} stack Stack() {
tos = -1;
class AccessTest {
public static void main(String[J
args) { Test ob= new Test(); // Push an item onto the
stack void push(int item) {
if(tOS==9)
// These are OK, a and b may be accessed directly System.out.println(''Stack is full.");
ob.a = 10 ; else
ob .b = 20; stck[++tos] = item;
}
else
return stck[tos--];
class TestStack {
public static void main(String[J
args) { Stack mystackl = new
Stack();
Stack mystack2 = new Stack();
Syste m.out.println("Stack in
mystack2
:"); for(int i=0; i<l0; i++)
System.out.println(mystack2.pop());
}
}
}
Understanding static
There will be times when you will want to define a class member that As soon as the UseStatic class is loaded, all of the static statements are
will be used independently of any object of that class .To create such a run. First, a is set to 3, then the static block executes, which prints a
member, precede its declaration with the keyword static. When a message and then initializes b to a*4 or 12. Then main( ) is called, which
member is declared static, it can be accessed before any objects of its calls meth(), passing 42 to x. The three println( ) statements refer to the
class are created, and without reference to any object. You can declare two static variables a and b, as well as to the parameter x.
both methods and variables to be static. The most common example of a Here is the output of the program:
static member is main(). main( ) is declared as static because it must be Static block initialized.
x = 42
called before any objects exist. a = 3
Instance variables declared as static are, essentially, global variables. b = 12
When objects of its class are declared, no copy of a static variable is Here is an example. Inside main( ), the static method callme( ) and the
made. Instead, all instances of the class share the same static variable. static variable b are accessed through their class name StaticDem
void test() {
Inner inner= new
Inner();
inner.display();
}
}
16. Explain how recursion is implemented win Java? What are the benefits of
recursion in programming?
17. Explain with a program, Java support for encapsulation through visibility
modifiers.
18. Explain the different roles of keyword ‘static’ with programs.
1. Write the general form of a class in Java. Explain class definition and member
access with suitable program. 19. Explain different roles of keyword ‘final’ with programs.
2. Explain two step procedure to create objects (class instance) with suitable 20. Explain the role of static nested classes and inner classes with programs.
program. 21. Develop a recursive version of generating, storing and display of Fibonacci series
3. Explain assignment of objects with suitable example. (Hint: use array).