0% found this document useful (0 votes)
9 views71 pages

6_7_Introducing Classes [Autosaved]

This document introduces the fundamentals of classes in programming, explaining that a class serves as a template for creating objects, which are instances of the class. It covers class definitions, access modifiers, instance variables, methods, constructors, and the concept of method overloading. Additionally, it discusses how to pass objects as parameters and the distinction between call-by-value and call-by-reference argument passing.

Uploaded by

sindhus121985
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)
9 views71 pages

6_7_Introducing Classes [Autosaved]

This document introduces the fundamentals of classes in programming, explaining that a class serves as a template for creating objects, which are instances of the class. It covers class definitions, access modifiers, instance variables, methods, constructors, and the concept of method overloading. Additionally, it discusses how to pass objects as parameters and the distinction between call-by-value and call-by-reference argument passing.

Uploaded by

sindhus121985
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/ 71

Module 2

Introducing Classes
Class Fundamentals….
2
• A class is a template that defines the form of an object.
• It specifies both the data and the code that will operate on that data.
• Objects are instances of a class.
• Thus, a class is essentially a set of plans that specify how to build an
object.
• The methods and variables that constitute a class are called members
of the class.
• The data members are also referred to as instance variables.
The General Form of a Class….
• A class is created by using the keyword class. The general form
3
of a
class definition is shown here:
<access modifier> class classname
{
<access modifier> type instance-var1;
<access modifier> type instance-var2;
// ...
<access modifier> type varN;
<access modifier> type method1(parameters)
{
// body of method
}
<access modifier> type method2(parameters)
{
// body of method
}
Access Modifiers 4

• Public: can be accessed any where.


• Protected: Can be accessed by all the class & subclass in
the same package and all the subclasses in other
package.
• Default: Can be accessed by all the class & subclass
within the same package.
• Private : can be accessed only within the class & thus
completely hidden from outside the class.
Defining a Class….
5
class Box
{
double width;
double height;
double depth;
}

 This class is called Box, and that defines three instance variables:
width, height, and depth
6

• A class definition creates a new data type.

• You will use this name to declare objects of type Vehicle.

• Remember that a class declaration is only a type description; it


does not create an actual object.
• To actually create a Vehicle object, you will use a statement like
the following:
Box mybox = new Box(); // create a Box object called mybox
• After this statement executes, mybox will be an instance
of Box.
7

• 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 general form of the dot operator is shown here:

object.member;
• For example, to assign the width variable of mybox the value
100, use the following statement
mybox.width = 100;
/* A program that uses the Box class. Call this file BoxDemo.java */
class Box
8
{
double width;
double height;
double depth;
}
class BoxDemo
{
public static void main(String args[])
{
Box mybox = new Box();//create box object
double vol; Volume is 3000.0
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
// This program declares two Box objects.
class Box 9

{
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;
10
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);
}
}

Volume is 3000.0 mybox1’s data is completely


Volume is 162.0 separate from the data contained in
mybox2.
Declaring objects:
11

Statement Effect
Box mybox; //declare reference to object null
mybox
This variable does not define an object.
Instead, it is simply a variable that can refer to an
object.

Box mybox = new Box() width


mybox height
in Java, all class objects must be depth
dynamically allocated
Box object
general form:
class-var = new classname ( );
Assigning Object Reference Variables… 12

• Object reference variables act differently than expected when an


assignment takes place.

Box b1 = new Box();


Box b2 = b1;

Width
b1 Height

Depth

b2 Box Object
Adding a Method to the Box Class…
13
general form of a method:
type name(parameter-list)
{
// body of method
}
class Box
{
double width;
double height;
double depth;

void volume()
{
System.out.println(" Volume is : ");
System.out.println(width * height * depth);
}
}
class BoxDemo
{ myBox1& 14
public static void main(String args[]) myBox2 are
{ Object for class
Box myBox1 = new Box(); Box
Box myBox2 = new Box();

myBox1.width = 10;
myBox1.height = 20;
myBox1.depth = 15; Displays the volume of the box
defined by myBox1
myBox2.width = 3;
myBox2.height = 6;
myBox2.depth = 9;
Displays the volume
of the box defined by
myBox1.volume();
myBox2
myBox2.volume();
}
}
Returning a value…
15

class Box
{
double width;
double height;
double depth;

double volume()
{
return width * height * depth;
}
}
class BoxDemo
{
public static void main(String args[]) 16
{
Box myBox1 = new Box();
Box myBox2 = new Box();
double vol;
myBox1.width = 10;
myBox1.height = 20;
myBox1.depth = 15;
myBox2.width = 3;
myBox2.height = 6; compute the volume of the box
myBox2.depth = 9; and return the result to the
caller.
vol = myBox1.volume();
System.out.println(“Volume is “ +vol);
// System.out.println(“ Volume is “ + myBox1.volume());

vol = myBox2.volume();
System.out.println(“Volume is “ +vol);
// System.out.println(“ Volume is “ + myBox1.volume());
}
}
17

• There are two important things to understand about


returning values:
• The type of data returned by a method must be
compatible with the return type specified by the
method.
• The variable receiving the value returned by a
method must also be compatible with the return type
specified for the method.
Adding a method That Takes Parameters…
18

• Parameters allow a method to be generalized.


int square() int square(int i)
{ {
return 10 * 10; return i * i ;
}
}

int x, y ;
x = square(5);
x = square(9);
y = 2;
x = square(y);
19
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.
• Once defined, the constructor is automatically called
immediately after the object is created.
• Constructors have no return type, not even void.
class Box
{ 20
double width; Constructor
double height;
double depth;
Box ()
{
System.out.println(" Constructing Box ");
width = 10;
height = 10;
depth = 10;
}

double volume()
{
return width * height * depth;
}
}
class BoxDemo6
{ 21

public static void main(String args[])


{
Box mybox1 = new Box ( );
Box mybox2 = new Box ( );
double vol;

vol = mybox1.volume( );
System.out.println(" Volume is "+vol);

vol = mybox2.volume( );
System.out.println(" Volume is +vol”); Constructing Box
Constructing Box
} Volume is 1000.0
Volume is 1000.0
}
22

• When we do not explicitly define a constructor for a


class, then Java creates a default constructor for the class.
• The default constructor automatically initializes all
instance variables to zero.
• The default constructor is often sufficient for simple
classes, but it usually won’t do for more sophisticated
ones.
Parameterized Constructors…..
class Box{ 23

double width; Constructor having


double height; parameters
double depth;

Box(double w, double h, double d)


{
width = w;
height = h;
depth = d;
}
double volume( )
{
return width * height * depth;
}
}
class BoxDemo7
{ 24

public static void main(String args[])


{
Box MyBox1 = new Box(10, 20, 15 );
Box MyBox2 = new Box( 3, 6, 9);
double vol;

vol = MyBox.volume( );
System.out.println(" Volume is "+vol);

vol = MyBox2 .volume( );


System.out.println(" Volume is +vol);
}
}
The this Keyword….
25
• Sometimes a method is needed to refer to the object that invoked it.
• It always reference to the object on which the method was invoked.
• To do this, Java defines this keyword.
• this can be used inside any method to refer to the current
object
• 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.

Box(double w, double h, double d) Box(double width, double height, double depth)


{ {
this.width = w; this.width = width;
this.height = h; this.height = height;
this.depth = d; this.depth = depth;
} }
Instance Variable Hiding
26
• Instance variable hiding refers to a state when instance variables
of the same name are present in superclass and subclass.
• 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.
• 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.
Box(double width, double height, double depth)
{
this.width = width;
this.height = height;
this.depth = depth;
}
Overloading Methods….
27

• 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.

• 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.
• The return type alone is insufficient to distinguish two versions of a
method.
class OverloadDemo
{
28
void trail()
{
System.out.println("No parameters") ;
}
void trail(int a)
{
System.out.println(" a " + a);
}
void trail(int a, int b)
{
System.out.println(" a and b: " + a +" " + b);
}
double trail(double a)
{
System.out.println("double a :"+ a) ;
return a*a;
}
}
class Overload
{ 29

public static void main(String args[])


{
OverloadDemo ob = new OverloadDemo();
double result;
ob.trail( );
ob.trail (10) ;
ob.trail(10, 20) ;
result = ob.trail(123.2) ; .
System.out.println("Result of ob.trail(123.2) :"+ result);
}
}
30

• When an overloaded method is called, Java looks for a match


between the arguments used to call the method and the method's
parameters.
• However, this match need not always be exact. In some cases
Java's automatic type conversions can play a role in overload
resolution.
class OverloadDemo
{ 31

void trail()
{
System.out.println(" No parameters");
}
void trail(int a, int b)
{
System.out.println(" a and b :"+a+" "+b);
}
void trail( double a)
{
System.out.println(" Inside trail(double) a:"+a);
}
}
class Overload
{ 32

public static void main(String args[ ])


{
OverloadDemo ob = new OverloadDemo( );
int i = 88;
ob.trail();
ob.trail(10, 20);
ob.trail(i); // this will invoke trail (double);
ob.trail(123.2) // this will invoke trail(double);
}
}
Overloading Constructors….
class Box { 33
double width, height, depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
Box() {
width = height = depth = -1; // use -1 to indicate an uninitialized box
}
Box(double len) {
width = height = depth = len;
}
double volume() {
return width * height * depth;
}
}
class OverloadCons {
public static void main(String args[]) { 34

Box mybox1 = new Box(10, 20, 15);


Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Using Objects as Parameters 35

 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.
// Objects may be passed to methods.
class Test { 36

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 37

{
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));
}
}
Argument Passing 38

 There are two ways that a computer language can pass


an argument to a subroutine.
 call-by-value
 call-by- reference
• call-by-value
39

• 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.
class Test {
void meth(int i, int j) 40

{
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);
}
} a and b before call: 15 20
a and b after call: 15 20
call-by- reference
41

• 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 Program for Objects are passed through their references.
42
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 PassObjRef 43

{
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);
}

ob.a and ob.b before call: 15 20


ob.a and ob.b after call: 30 10
Returning Objects 44

• 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..
// Returning an object.
45
class Test
{
int a;
Test(int i)
{
a = i;
}
Test incrByTen()
{
Test temp = new Test(a+10);
return temp;
}
}
class RetOb
46
{
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);
}
}
Recursion 47

 Java supports recursion. Recursion is the process of


defining something in terms of itself.

 As it relates to Java programming, recursion is the


attribute that allows a method to call itself.

 A method that calls itself is said to be recursive.


Recursion…
class Factorial { 48
int fact(int n)
{
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
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));
}
}
Introducing Access Control 49
• encapsulation links data with the code that manipulates it.
• encapsulation provides another important attribute: access control.
• Through encapsulation, you can control what parts of a program
can access the members of a class. By controlling access, you can
prevent misuse.
• allowing access to data only through a well-defined set of
methods, can prevent the misuse of that data.
• Thus, when correctly implemented, a class creates a “black
box” which may be used, but the inner workings of which are
not open to tampering
Introducing Access Control 50

• Java’s access specifiers are public, private, and protected.


• Java also defines a default access level.
• protected applies only when inheritance is involved.
• Public: When a member of a class is modified by the public
specifier, then that member can be accessed by any other code.
• Private: When a member of a class is specified as private, then
that member can only be accessed by other members of its class.
• When no access specifier is used, then by default the member of a
class is public within its own package, but cannot be accessed
outside of its package.
Access Specifiers
/* This program demonstrates the difference between public and private. */ 51
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;
}
}
class AccessTest
{
52
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;

// ob.c = 100; // This is not OK and will cause an error


// You must access c through its methods
ob.setc(100); // OK

System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc());
}
}
Understanding static….
• There will be times when you will want to define a class member
53

that will be used independently of any object of that class.


• But normally members are accessed by the objects.
• It is possible to create a member that can be used by itself,
without reference to a specific instance.
• To create such a member, precede its declaration with the
keyword static.
• When a member is declared static, it can be accessed before any
objects of its class are created, and without reference to any
object.
• Both methods and variables can be declared static.
• main() is declared as static because it must be called before any
objects exist.
Methods declared as static have several restrictions: 54

• They can only call other static methods.


• They must only access static data.
• They cannot refer to this or super in any way.
// Demonstrate static variables, methods, and blocks.
class UseStatic {
55
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);
}
}
56

• If we wish to use the static methods and variables outside of the


class, to do so, we need only specify the name of class followed by
the dot operator.

classname.method()
• Here, classname is the name of the class in which the static method
is declared.
• A static variable can be accessed in the same way by use of the dot
operator on the name of the class.
class StaticDemo
{ 57

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);
}
}
Introducing final
58

• A variable can be declared as final.


• It prevents its contents from being modified.
• must initialize a final variable when it is declared.
For example: 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;

The keyword final can also be applied to methods, but its


meaning is substantially different than when it is applied to
variables
Nested & Inner Classes….
59

• It is possible to define a class within another class; such classes


are known as nested classes.
• The scope of a nested class is bounded by the scope of its
enclosing class. Thus, if class B is defined within class A, then B
is known to A, but not outside of A.
• A nested class has access to the members, including private
members, of the class in which it is nested.
• However, the enclosing class does not have access to the members
of the nested class.
class Outer
{
int outer_x = 100; 60

class Inner // this is an innner class


{
void display()
{
System.out.println("display: outer_x = " + outer_x);
}
}

void test()
{
Inner inner = new Inner();
inner.display();
}
}
class InnerClassDemo
{ 61

public static void main(String args[])


{
Outer outer = new Outer();
outer.test();
}
}
• There
62

are two types of nested classes: static and inner. A


static nested class is one which has the static modifier applied.
• Because it is static, it must access the members of its enclosing
class through an object. That is it cannot refer to members of its
enclosing class directly.
• An inner class is a non-static nested class.
• It has access to all of the variables and methods of its outer class
and may refer to them directly in the same way that other non-
static members of the outer class do.
• Thus, an inner class is fully within the scope of its enclosing
class.
// This program will not compile.
class Outer
{ 63

int outer_x = 100;


class Inner
{
int y = 10; // y is local to Inner
void display()
{
System.out.println("display: outer_x = " + outer_x);
}
}
void test()
{
Inner inner = new Inner();
inner.display();
}
void showy()
{
System.out.println(y); // error, y not known here!
}
}
class InnerClassDemo
{ 64

public static void main(String args[])


{
Outer outer = new Outer();
outer.test();
}
}
// Define an inner class within a for loop.
class Outer
{ 65

int outer_x = 100;


void test()
{
for(int i=0; i<10; i++)
{
class Inner
{
void display()
{
System.out.println("display: outer_x = " + outer_x);
}
}
Inner inner = new Inner();
inner.display();
}
}
}
class InnerClassDemo
{ 66

public static void main(String args[])


{
Outer outer = new Outer();
outer.test();
}
}
67

An Instance of InnerClass Exists Within an Instance of OuterClass


Garbage collection 68

• Allocation using new()


• Deallocation done 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.
• Garbage collection only occurs sporadically (if at all) during the
execution of your program.
The finalize( ) Method 69

• an object will need to perform some action when it is destroyed.


• Ex:an object is holding some non-Java resource such as a file
handle or character font, then want to make sure these resources
are freed before an object is destroyed.
• Java provides a mechanism called finalization.
• By using finalization, can define specific actions that will occur
when an object is just about to be reclaimed by the garbage
collector.
The finalize( ) Method 70

• To add a finalizer to a class, define the finalize( ) method.


• The Java run time calls that method whenever it is about to recycle
an object of that class.
• Inside the finalize( ) method, specify those actions that must be
performed before an object is destroyed.
• 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:
71

protected void finalize( )


{
// finalization code here
}

You might also like