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

Unit 3-1

Uploaded by

cja4326
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Unit 3-1

Uploaded by

cja4326
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Introducing Classes

By. Dr. Kiran K. Tangod


Prof. & Head
Dept of ISE, GIT, Belagavi
Class Fundamentals
• The class is at the core of Java.
• It is the logical construct upon which the entire Java language is built
because it defines the shape and nature of an object.
• A class is that it defines a new data type. Once defined, this new type
can be used to create objects of that type.
• A class is a template for an object, and an object is an instance of a
class.
The General Form of a Class

• When class is defined, it gives exact class classname {


type instance-variable1;
form and nature of class. type instance-variable2;
• Nature of class is defined by // ...
type instance-variableN;
specifying the data that it contains type methodname1(parameter-list) {
and the code that operates on that // body of method
data. }
type methodname2(parameter-list) {
• A class is declared by use of the class // body of method
}
keyword. // ...
• A simplified general form of a class type methodnameN(parameter-list) {
// body of method
definition is shown here: }
}
Class fundamentals
• The data, or variables, defined within a class are called instance
variables.
• Variables defined within a class are called instance variables because
each instance of the class (that is, each object of the class) contains
its own copy of these variables.
• The code is contained within methods.
• Collectively, the methods and variables defined within a class are
called members of the class.
A Simple Clas class Box {
double width;
double height;
double depth;
}
Declaring Objects
• Objects are created in two steps
• First, declare a variable of the class type. This variable does not define an
object. Instead, it is simply a variable that can refer to an object.
• 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 (that is, allocates at run time)
memory for an object and returns a reference to it.
Example:
Box mybox = new Box();
OR
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
Closer look at new
Assigning Object Reference Variables
Box b1 = new Box();
Box b2 = b1;
• The assignment of b1 to b2 did not allocate any memory or copy any part
of the original object. It simply makes b2 refer to the same object as does
b1.
• Any changes made to the object through b2 will affect the object to
which b1 is referring, since they are the same object.
Introducing Methods
General form of a method:
type name(parameter-list)
{
// body of method
}
• type specifies the type of data returned by the method
• The name of the method is specified by name.
• The parameter-list is a sequence of type and identifier pairs separated by
commas.
• Parameters are essentially variables that receive the value of the
arguments passed to the method when it is called. If the method has no
parameters, then the parameter list will be empty
• Methods that have a return type other than void return a value to
the calling routine using the following form of the return statement:
return value;
• Here, value is the value returned.
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.
• The constructor is automatically called immediately after the object
is created, before the new operator completes.
• Constructors have no return type, not even void. This is because the
implicit return type of a class’ constructor is the class type itself.
• It is the constructor’s job to initialize the internal state of an object so
that the code creating an instance will have a fully initialized, usable
object immediately.
Constructor: example
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;
}
}
Box Class
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;
}
}
The this Keyword
• this keyword is used 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.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
Instance Variable Hiding
• It is illegal in Java to declare two local variables with the same name inside
the same or enclosing scopes.
• Local variables can be declared, including formal parameters to methods,
which overlap with the names of the class’ instance variables.
• When a local variable has the same name as an instance variable, the local
variable hides the instance variable.
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Garbage Collection
• Objects are dynamically allocated by using the new operator.
• In languages, such as C++, dynamically allocated objects must be manually
released by use of a delete operator.
• Java takes a different approach; it handles deallocation for you
automatically.
• The technique that accomplishes this is called garbage collection.
• It works like this:
• 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.
• There is no explicit need to destroy objects as in C++.
• Garbage collection only occurs sporadically (if at all) during the execution of your
program.
• It will not occur simply because one or more objects exist that are no longer used.
• Different Java run-time implementations will take varying approaches to garbage
collection.
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 character font, then it is required to make sure that
these resources are freed before an object is destroyed.
• To handle such situations, Java provides a mechanism called
finalization.
• Using finalization, specific actions can be implemented that will occur
when an object is just about to be reclaimed by the garbage collector.
• Inside the finalize( ) method, you will specify those actions that must
be performed before an object is destroyed.
The finalize( ) Method
• The garbage collector runs periodically, checking for objects that are
no longer referenced by any running state or indirectly through other
referenced objects. Right before an asset is freed,
• the Java run time calls the finalize( ) method on the object.
• The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
A Stack Class

// This class defines an integer stack // Push an item onto the stack // Pop an item from the stack
that can hold 10 values. int pop() {
void push(int item) {
class Stack { if(tos < 0) {
if(tos==9)
int stck[] = new int[10]; System.out.
System.out. println("Stack
int tos; println("Stack is full. underflow.");
// Initialize top-of-stack "); return 0;
Stack() { else }
tos = -1; else
stck[++tos] = item;
} return stck[tos--];
} }
}
This program generates the following output:
class TestStack { Stack in mystack1:
public static void main(String args[]) { 9
Stack mystack1 = new Stack(); 8
7
Stack mystack2 = new Stack();
6
// push some numbers onto the stack 5
for(int i=0; i<10; i++) mystack1.push(i); 4
for(int i=10; i<20; i++) mystack2.push(i); 3
2
// pop those numbers off the stack 1
System.out.println("Stack in mystack1:"); 0
for(int i=0; i<10; i++) Stack in mystack2:
System.out.println(mystack1.pop()); 19
18
System.out.println("Stack in mystack2:"); 17
for(int i=0; i<10; i++) 16
System.out.println(mystack2.pop()); 15
} 14
13
} 12
11
10
A Closer Look at Methods and Classes :
Overloading Methods

• In Java it is possible to define two or more methods within the same


class that share the same name
• Parameter declarations must be different for every method.
• These methods sharing same name are said to be overloaded.
• This process is referred to as method overloading.
• Method overloading is one of the ways to implement 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.
Example for method overloading
// Demonstrate method overloading. // Overload test for two integer parameters.

class OverloadDemo { void test(int a, int b) {


void test() { System.out.println("a and b: " + a + " " +
b);
System.out.println("No
}
parameters"); // overload test for a double parameter
} double test(double a) {
// Overload test for one integer parameter. System.out.println("double a: " + a);
void test(int a) { return a*a;
System.out.println("a: " + a); }
}
}
class Overload { This program generates the following output
public static void main(String args[]) { No parameters
OverloadDemo ob = new OverloadDemo(); a: 10
double result; a and b: 10 20
double a: 123.25
// call all versions of test()
Result of ob.test(123.25): 15190.5625
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Overloading Constructors
In addition to overloading normal methods, // constructor used when no dimensions specified
you can also overload constructors Box() {
class Box { width = -1; // use -1 to indicate
double width; height = -1; // an uninitialized
double height; depth = -1; // box
double depth; }
// constructor used when all dimensions specified // constructor used when cube is created
Box(double w, double h, double d) { Box(double len) {
width = w; width = height = depth = len;
height = h; }
depth = d; // compute and return volume

} double volume()
{ return width * height * depth;
}
}
Using Objects as Parameters
class PassOb {
// Objects may be passed to methods.
public static void main(String args[]) {
class Test { Test ob1 = new Test(100, 22);
int a, b; Test ob2 = new Test(100, 22);
Test(int i, int j) { Test ob3 = new Test(-1, -1);
a = i; System.out.println("ob1 == ob2: " + ob1.equals(ob2));
b = j; }
} }
// return true if o is equal to the
invoking object This program generates the following output:
boolean equals(Test o) { ob1 == ob2: true
if(o.a == a && o.b == b) return true; ob1 == ob3: false
else return false;
}
}
A Closer Look at Argument Passing
• In general, there are two ways that a computer language can pass an
argument to a subroutine.
• The first way is call-by-value. This approach copies the value of an
argument into the formal parameter of the subroutine. Therefore,
changes made to the parameter of the subroutine have no effect on
the argument.
• The second way an argument can be passed is call-by-reference. In
this approach, a reference to an argument (not the value of the
argument) is passed to the parameter. Inside the subroutine, this
reference is used to access the actual argument specified in the call.
This means that changes made to the parameter will affect the
argument used to call the subroutine.
• Java uses both approaches, depending upon what is passed.
A Closer Look at Argument Passing: Call by value

• call-by-value: is implemented in class CallByValue {


java by using primitive data types public static void main(String args[]) {
for passing parameters. Test ob = new Test();
int a = 15, b = 20;
• class Test { System.out.println("a and b before call: " +
• void meth(int i, int j) { a + " " + b);
ob.meth(a, b);
• i *= 2; System.out.println("a and b after call: " +
• j /= 2; a + " " + b);
}
• } }
• } • The output from this program is shown here:
a and b before call: 15 20
a and b after call: 15 20
A Closer Look at Argument Passing: Call by reference
• Call by reference is implemented by passing an object to a method
• Objects are passed by what is effectively call-by-reference
• When a variable of a class type is created, reference to an object gets
created.
• When object reference is passed to a method, the parameter that
receives it will refer to the same object as that referred to by the
argument.
• This effectively means that objects are passed to methods by use of
call-by-reference.
• Changes to the object inside the method do affect the object used as
an argument.
Call by reference Example:
// Objects are passed by class CallByRef {
reference.
public static void main(String args[]) {
class Test { Test ob = new Test(15, 20);
int a, b; System.out.println("ob.a and ob.b before call: " + ob.a + “ " + ob.b);
Test(int i, int j) { ob.meth(ob);
a = i; System.out.println("ob.a and ob.b after call: " +ob.a + " " + ob.b);
b = j; }
} }
// pass an object This program generates the following output:
void meth(Test o) { ob.a and ob.b before call: 15 20
o.a *= 2; ob.a and ob.b after call: 30 10
o.b /= 2;
}
}
Returning Objects
• A method can return any type class RetOb {
public static void main(String args[]) {
of data, including class types. Test ob1 = new Test(2);
// Returning an object. Test ob2;
ob2 = ob1.incrByTen();
class Test { System.out.println("ob1.a: " + ob1.a);
int a; System.out.println("ob2.a: " + ob2.a);
Test(int i) { ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: "
a = i; + ob2.a);
} }
}
Test incrByTen() {
Test temp = new Test(a+10); The output generated by this program is shown here:
ob1.a: 2
return temp;
ob2.a: 12
} ob2.a after second increase: 22
}
Recursion
• Java supports recursion.
• Recursion is the process of defining something in terms of itself.
• A method that calls itself is said to be recursive.
• The classic example of recursion is the computation of the factorial of
a number.
• The factorial of a number N is the product of all the whole numbers
between 1 and N. For example, 3 factorial is 1 × 2 × 3, or 6.
Recursion example:
class Recursion {
public static void main(String args[]) {
// A simple example of recursion. Factorial f = new Factorial();
class Factorial { System.out.println("Factorial of 3 is " + f.
// this is a recursive method fact(3));
int fact(int n) { System.out.println("Factorial of 4 is " + f.
fact(4));
int result;
System.out.println("Factorial of 5 is " + f.
if(n==1) return 1; fact(5));
result = fact(n-1) * n; }
return result; }
}
} The output from this program is shown here:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
Access control
• Encapsulation links data with the code that manipulates it.
• Encapsulation provides another important attribute ie. access control.
• Through encapsulation, it is possible to control what parts of a program
can access the members of a class.
• By controlling access, you can prevent misuse.
• By allowing access to data only through a well defined set of methods,
it is possible to prevent the misuse of that data.
• With access control class creates a “black box” which may be used, but
the inner workings of which are not open to tampering.
Access control
• Accessibility of member is determined by the access specifier that
modifies its declaration.
• Java supplies a rich set of access specifiers. Some aspects of access
control are related mostly to inheritance or packages. (A package is,
essentially, a grouping of classes.)
• Java’s access specifiers are public, private, and protected. Java also
defines a default access level. protected applies only when inheritance is
involved.
• When a member of a class is modified by the public specifier, then that
member can be accessed by any other code.
• When a member of a class is specified as private, then that member can
only be accessed by other members of its class.
class AccessTest {
class Test { public static void main(String args[]) {
int a; // default access Test ob = new Test();
public int b; // public access // These are OK, a and b may be accessed directly
private int c; // private access ob.a = 10;
// methods to access c ob.b = 20;
void setc(int i) { // set c's value // This is not OK and will cause an error
c = i; // ob.c = 100; // Error!
} // You must access c through its methods
int getc() { // get c's value ob.setc(100); // OK
return c; System.out.println("a, b, and c: " + ob.a + " " +
} ob.b + " " + ob.getc());
} }
}
Static modifier
• Static member is a class member that will be used independently of
any object of that class.
• Non static class member must be accessed only in conjunction with
an object of its class.
• When a member is declared static, it can be accessed before any
objects of its class are created, and without reference to any object.
• Both methods and variables to be declared static.
• The most common example of a static member is main( ). main( ) is
declared as static because it must be called before any objects exist
Static modifier
• Instance variables declared as static are, essentially, global variables.
When objects of its class are declared, no copy of a static variable is
made. Instead, all instances of the class share the same static
variable.
• Methods declared as static have several restrictions:
• They can only call other static methods.
• They must only access static data.
• They cannot refer to this or super in any way. (The keyword super relates to
inheritance)
• To initialize static variables, static block has to be declared that gets
executed exactly once, when the class is first loaded.
Example
// Demonstrate static variables,
methods, and blocks.
static {
class UseStatic { System.out.println("Static block
static int a = 3; initialized.");
static int b; b = a * 4;
}
static void meth(int x) {
public static void main(String args[]) {
System.out.println("x = " + x); meth(42);
System.out.println("a = " + a); } Output:
System.out.println("b = " + b); } Static block initialized.
x = 42
}
a=3
b = 12
Order of execution of static statements:
• As soon as the UseStatic class is loaded, all of the static statements are run. First,
a is set to 3,then the static block executes, which prints a message and then
initializes b to a*4 or 12.
• Then main( ) is called, which calls meth( ), passing 42 to x. The three println( )
statements refer to the two static variables a and b, as well as to the local variable
x.

• Outside of the class in which they are defined, static methods and variables can
be used independently of any object. To do so, only specify the name of their
class followed by the dot operator. For example, to call a static method from
outside its class,
General form :
classname.method( )
final keyword:
• 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.
• Examples:
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;
Arrays Revisited
• Arrays are implemented as objects.
• Because of this, there is a special array attribute that you will want to
take advantage of.
• Specifically, the size of an array that is, the number of elements that
an array can hold is found in its length instance variable.
• All arrays have this variable, and it will always hold the size of the
array.

You might also like