Basics of Java Programming
Unit-III
22PLC25C
K.S.Mathad
Introducing Classes
• You do this by specifying the data that it contains
and the code that operates on that data.
• While very simple classes may contain only code
or only data, most real-world classes contain
both.
• A class is declared by use of the class keyword.
• The data, or variables, defined within a class are
called instance variables. The code is contained
within methods.
• the methods and variables defined within a class
are called members of the class.
K.S.Mathad
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
THE JAVA LANGUAGE
// ...
type methodnameN(parameter-list) {
// body of method
}
}
K.S.Mathad
Class
• Most methods will not be specified as static or
public. Notice that the general form of a class
does not specify a main( ) method. Java
classes do not need to have a main( ) method.
• You only specify one if that class is the starting
point for your program.
K.S.Mathad
A Simple Class
• Here is a class called Box that defines three
instance variables: width, height, and depth.
Currently, Box does not contain any methods
(but some will be added soon)
class Box {
double width;
double height;
double depth;
}
K.S.Mathad
Class and object
• It is important to remember that a class
declaration only creates a template; it does not
create an actual object.
• To actually create a Box object, you will use a
statement like the following:
Box mybox = new Box(); // create a Box object
called mybox
• Every Box object will contain its own copies of the
instance variables width, height, and depth.
• The dot operator links the name of the object
with the name of an instance variable.
mybox.width = 100;
K.S.Mathad
/* A program that uses the Box class. Call this file BoxDemo.java*/
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
} K.S.Mathad
// This program declares two Box objects.
class Box {
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
} K.S.Mathad
Declaring Objects
• The new operator dynamically allocates (that
is, allocates at run time) memory for an
object and returns a reference to it.
• This reference is then stored in the variable.
Box mybox = new Box();
• This statement combines the two steps
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
K.S.Mathad
Object
K.S.Mathad
Assigning Object Reference Variables
Box b1 = new Box();
Box b2 = b1;
• b1 and b2 will both refer to the same object.
• A subsequent assignment to b1 will simply unhook b1
from the original object without affecting the object or
affecting b2.
Box b1 = new Box();
Box b2 = b1; // ...
b1 = null;
Here, b1 has been set to null, but b2 still points to the original object.
K.S.Mathad
Introducing Methods
type name(parameter-list) {
// body of method
}
K.S.Mathad
Adding a Method to the Box Class
class Box {
double width;
double height;
double depth;
// display volume of a box
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
K.S.Mathad
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// display volume of first box
mybox1.volume();
// display volume of second box
mybox2.volume();
}
} K.S.Mathad
Returning a Value
// Now, volume() returns the volume of a
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
}
K.S.Mathad
class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
K.S.Mathad
Constructors
• 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.
• Constructors look a little strange because they
have no return type, not even void.
K.S.Mathad
/* Here, Box uses a constructor to initialize the dimensions of a box.*/
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
K.S.Mathad
O/P
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
K.S.Mathad
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
K.S.Mathad
Parameterized Constructors
class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
K.S.Mathad
Parameterized Constructors
/* Here, Box uses a parameterized constructor to initialize the
dimensions of a box.*/
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
} K.S.Mathad
The this Keyword
• This can be used inside any method to refer to
the current object.
• You can use this anywhere a reference to an
object of the current class type is permitted.
// A redundant use of this.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
K.S.Mathad
Instance Variable Hiding
// Use this to resolve name-space collisions.
• width would have referred to the formal
parameter, hiding the instance variable width.
Box(double width, double height, double depth)
{
this.width = width;
this.height = height;
this.depth = depth;
}
K.S.Mathad
Garbage collection
• it handles deallocation for you automatically.
The technique that accomplishes this is called
garbage collection.
• when no references to an object exist, that
object is assumed to be no longer needed,
and the memory occupied by the object can
be reclaimed.
K.S.Mathad
The finalize( ) Method
• Sometimes an object will need to perform some action
when it is destroyed.
• For example, if an object is holding some non-Java
resource such as a file handle or window character font,
then you might want to make sure these resources are
freed before an object is destroyed.
• By using finalization, you can define specific actions that
will occur when an object is just about to be reclaimed
by the garbage collector.
• The Java run time calls that method whenever it is about
to recycle an object of that class. Inside the finalize( )
method you will specify those actions that must be
performed before an object is destroyed.
K.S.Mathad
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
K.S.Mathad
A Stack Class
• A stack stores data using first-in, last-out
ordering.
• Stacks are controlled through two operations
traditionally called push and pop.
K.S.Mathad
// This class defines an integer stack that can hold 10 values.
class Stack {
int stck[] = new int[10];
int tos;
Stack() { // Initialize top-of-stack
tos = -1;
}
void push(int item) { // Push an item onto the stack
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
int pop() { // Pop an item from the stack
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
K.S.Mathad
}
O/P
Stack in mystack1: Stack in mystack2:
9 19
8 18
7 17
6 16
5 15
4 14
3 13
2 12
1 11
0 10
K.S.Mathad
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
// push some numbers onto the stack
for(int i=0; i<10; i++) mystack1.push(i);
for(int i=10; i<20; i++) mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());
}
}
K.S.Mathad
A Closer Look at Methods and Classes
• Overloading Methods
– it is possible to define two or more methods
within the same class that share the same name,
as long as their parameter declarations are
different.
– Method overloading is one of the ways that Java
implements 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.
K.S.Mathad
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
K.S.Mathad
// Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
}
K.S.Mathad
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
}
}
K.S.Mathad
// Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
} K.S.Mathad
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
K.S.Mathad
Overloading Constructors
• In addition to overloading normal methods,
you can also overload constructor methods.
K.S.Mathad
/* Here, Box defines three constructors to initialize
the dimensions of a box various ways. Last is with double parameters
*/
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
K.S.Mathad
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
K.S.Mathad
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// 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 vol = mycube.volume();
System.out.println("Volume of mycube is " + vol); }
}
K.S.Mathad
Using Objects as Parameters
// Objects may be passed to methods.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
K.S.Mathad
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));
}
}
K.S.Mathad
// 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;
}
K.S.Mathad
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
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);
}
}
K.S.Mathad
// 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;
}
}
K.S.Mathad
A Closer Look at Argument Passing
• There are two ways that a computer language
can pass an argument to a subroutine.
• The first way is call-by-value: This method
copies the value of an argument into the
formal parameter of the subroutine.
• The second way an argument can be passed is
call-by-reference: a reference to an argument
(not the value of the argument) is passed to
the parameter.
K.S.Mathad
// Simple types are passed by value.
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " + a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " + a + " " + b);
}
}
K.S.Mathad
// Objects are passed by reference.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +
ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +
ob.a + " " + ob.b);
}
} K.S.Mathad
outputs
The output for call by value program is shown here:
a and b before call: 15 20
a and b after call: 15 20
The output for call by reference program is shown
here:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
K.S.Mathad
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: "
+ ob2.a);
}
}
K.S.Mathad
Returning Objects
// Returning an object.
class Test {
int a;
Test(int i) {
a = i;
}
Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}
}
K.S.Mathad
• Recursion is the process of defining something in
terms of itself.
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
K.S.Mathad
Recursion
// A simple example of recursion.
class Factorial {
// this is a recursive function
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
K.S.Mathad
Introducing Access Control
• Encapsulation links data with the code that
manipulates it.
• Through encapsulation, you can control what
parts of a program can access the members of a
class.
• a member can be accessed is determined by the
access specifier.
• Java’s access specifiers are public, private, and
protected.
• private, means member can only be accessed by
other members of its class.
• protected applies only when inheritance is
involved.
K.S.Mathad
/* This program demonstrates the difference between
public and private.
*/
class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c;
}
}
K.S.Mathad
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // O
System.out.println("a, b, and c: " + ob.a + " " +
ob.b + " " + ob.getc());
}
}
K.S.Mathad
Understanding static
• Normally a class member must be accessed
only in conjunction with an object of its class.
However, it is possible to create a member
that can be used by itself, without reference to
a specific instance.
• To create such a member, precede its
declaration with the keyword static.
• You can declare both methods and variables
to be static.
K.S.Mathad
Static
• Methods declared as static have several
restrictions:
– They can only call other static methods.
– They must only access static data.
– They cannot refer to this or super in any way.
K.S.Mathad
// Demonstrate static variables, methods, and blocks.
class UseStatic {
static int a = 3;
static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
K.S.Mathad
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}
class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
K.S.Mathad
Introducing final
• A variable can be declared as final. Doing so
prevents its contents from being modified. This
means that you must initialize a final variable
when it is declared.
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
• It is a common coding convention to choose all
uppercase identifiers for final variables. Variables
declared as final do not occupy memory on a per-
instance basis. Thus, a final variable is essentially
a constant. K.S.Mathad
Arrays Revisited
// This program demonstrates the length array member.
class Length {
public static void main(String args[]) {
int a1[] = new int[10];
int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};
int a3[] = {4, 3, 2, 1};
System.out.println("length of a1 is " + a1.length);
System.out.println("length of a2 is " + a2.length);
System.out.println("length of a3 is " + a3.length);
}
}
K.S.Mathad