0% found this document useful (0 votes)
4 views38 pages

Chapter6 Classes

The document provides an overview of classes in Java, explaining their structure, instance variables, and methods. It discusses the creation of objects, the role of constructors, and the use of the 'this' keyword for referencing instance variables. Additionally, it covers garbage collection, finalization, and the encapsulation concept through class design, using a stack class as an example.

Uploaded by

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

Chapter6 Classes

The document provides an overview of classes in Java, explaining their structure, instance variables, and methods. It discusses the creation of objects, the role of constructors, and the use of the 'this' keyword for referencing instance variables. Additionally, it covers garbage collection, finalization, and the encapsulation concept through class design, using a stack class as an example.

Uploaded by

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

Classes

What is Class?
 Class is core-basic construction upon which
entire Java language is built.
 The class is an template for an object.and an object is an instance of an class.

 When you define class you declare its exact form and nature because you
define data members and member functions of that class
General form :
class classname
{
Type instance – variable 1;
Type instance – variable 2;
//
Type instance variableN;

Type methodname1(parameter list){


Body of method;
}

Type methodnameN(paramer-list){
Body of method;
}
}
 The data or variables defined within the class are called
instance variables.
 Because Each instance(each object) of the class contains its own
copy of variables.
 So the data for one object is separate from data for another.
 Code is contained within methods.Collectively,the methods and
variables defined Within a class are called members of a class
 Not all methods like main(),will have public or static.
 General form of class does not specify main method.-main method
is not Compulsory For all classes.
 Only one of its class – to be starting point of program,should have
main() method.
 Further ,applets don’t require main() method at all.

 Unlike C++,class declaration and method implementation is done in class itself-


all in one Place.This sometimes makes very large java source files but it is
compulsory that any Class must be defined in a single source file.

 After a long run all declaration and definition – at one place makes it easier
to maintain.
A Simple class
class Box{ ///declares class with 3 instance variables
double width;
double height;
double depth;
}

//Creating object
box mybox = new Box(); // create a box object called mybox

mybox.width = 100;

Create main() method and then you have to call this to initailize the width,height and
depth.

To compute volume,simply write (And display the volume):


Vol = mybox.width * mybox.height * mybox.depth;
Declaring objects
 When you create a class , you are creating a new data type.
 You can use this type to declare objects of that type.For this,

 Step1. You must declare variable of that class


 classname object_name;

 Step 2.You must first acquire an actual physical copy of the


object and assign it to that variable – use new

Object_name = new class_name; //new allocates memory to


object at runtime and returns a reference to it.(address of object)
Statement Effect
Box mybox; null

Width
Mybox = new Box(); Height
Depth
mybox

Box object
 Object references appear to be similar to pointers .
 This suspiction is essentially correct.
 An object reference is similar to a memory pointer.
 Main difference – is that you cannot manipulate references as you
can actual Pointers.
 Thus you cannot cause an object reference to point to an arbitary
Memory location or manipulate it like an integer.
A closer look at new
Class-var = new classname() // dynamially
allocates moemory to object(class variable)

 Opening and closing braces- () defines what occurs when object of


class is created.
 Constructors are an important part of all classed and have many
significant attributes.

 We can define our own constructor. But if no one is defined then


java will automatically Supply a default constructor.
 new is not used for int/chars because Java’s simple types are not
implemented as Objects.-for efficiency.
 For objects,java has to treat them differently.

 Because memory is allocated at run time,you can allocate as many


or as few objects As it needs during the execution of your program.
 Since memory is finite,it may happen that run time exception will
occur.
 Class creates a logical framework that defines the relationship
between its members.
 When you create an object of class , you are creating an instance
of class.

 So class is logical construct.

 Object is physical entity because object occupies (physically )


 space in memory.
Assigning object reference variables:

Box b1= new Box();


Box b2 = b1;

B2 and b1 are both pointing to same object.


Introducing methods
Java gives methods so much power and flexibility .

General form:
type name(parameter-list )

Type ->data type returned by method.If it is not returning


anything,its return type must be void

Name : is the name of method.It is any valid identifier other than


those already used by other items within current scope.
Parameter-list is a sequence of type and identifier pairs seperated
by commas.

Parameters are essentially a variables that receive the value of the


arguments passed to the method when it is called.

If the method has no parameters,parameters list will be empty.


Method that have 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.


Adding the method to the box class :

Most of the times you will use methods to access the instance
variables Defined by the class.

Method helps class implementer to hide the specific layout of internal


Data Structure behind cleaner method abstractions.

In addition to defining methods that provide access to data ,you can


also define Methods that are used internally by the class itself.
Method of box class

Void volume(){
System.out.println(“Volume is :”+width*depth*height);
}

//Call method :
mybox1.volume(); // volume of mybox1-values of width hight
and depth of mybox1
mybox2.volume();//volume of mybox2
Adding a method that takes parameters :
int square ( int i )
{
return i*i ;
}

This implementation is used in the case like when you pass a


parameter (call a method )
As below :
int x,y;
x = square(5);
y = square(9);

So everytime you get square of new number that you pass


as parameter .
Constructors
 It can be tedius to initialize all of the variables in a
class each time an instance(object ) Is created
Because the requirement of initialization is so
common,Java allows objects to initialize themselves when
they are created.

Automatic initialization is performed by the use of constructor.


Properties :
Same name as class
No return type – not even void because implicit return type of class is
class type itself.
Immediately called when object of that class is created,before the new
operator completes.

Example :
Box()
{
width = 10;
height =10;
depth = 10;
}
If you will create two box objects,then they both will have all
three instance variable Values,i.e.width = 10,height =
10,depth=10;

Box mybox1 = new Box();


Box mybox2 = new Box();

To avoid this,we use parameterized constructor.


Because what is needed is way to construct Box with various
dimensions
Syntax:

Classname(parameter1,parameter2,…)
{
var1 = parameter1;
var2 = parameter2;
//…so on
}
The 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 always a reference to the object on which the
method was invoked.
 You can use this anywhere a reference to an object of the class type
is permitted.
Box(double w, double h,double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
Example
Class Box
{ double width;
double height;
double depth;
}
//Constructor for box
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
Instance variable hiding
You cannot have two local variables with the same name
inside the same or enclosing scopes.

However when a local variable has the same name as an instance


variable ,the local variable hides the instance variable.

Box(double width,double height,double depth)


{
this.width = width;
this.height = height;
this.depth = depth;
}
The use of this can sometimes be confusing and some programmers
are careful not to use local variables and formal parameter
names that hide instance variables.

While 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.
Garbage collection
In some languages like C++ dynamically
allocated objects must be manually released
By use of delete operator.

Java takes different approach..it handles deallocation for you


automatically.

The technique that handles this is called garbage collection.

It works like this : when no reference to the object exists, that


object is assumed to no longer needed,and the memory occupied
by the object is reclaimed
There is no explicit need to destroy objects as in C++.
The finalize() method
Sometimes an object will need to perform some action when it is
destroyed.
For example,if an object is holding non java resource such as file
handle or window
Character font , then you might want to make sure these resources
are freed before an object is destroyed.

To handle such situations ,Java provides a mechanism called


finalization.
By using finalization you can define specific actions that will occur
when an object is just about to be reclaimed by the garbage collector.
protected void finalize( )
{
//finalization code here
}
Finalize() is called just prior to garbage collection :
It is not called when an object goes out-of-scope for example .

You cannot know when – or even if finalize() will be


executed.Therefore your program should provide other means of
releasing system resources used by the object.

It must not rely on finialize() for normal program operation.


 In C++,it allows programmer define a destructor for a class
that is called when an object goes out of scope.

 Java does not provide destructor.

 The finalize() method only approximates the need for


the destructor.

 In Java,need for destructor is minimal because Java’s garbage


collector subsystem.
A stack class
A class is an mechanism by which
encapsulation is achieved in Java.

By creating a class , you are creating a new data type that defines
both the nature of the data being manipulated and the routines
used to manipulate it.

Further the methods define a consistent and controlled interface


to class’ data.
So you can use the class through its methods without having to
worry about its Detailed implementation.
Class is like data engine.
No knowledge of what goes on inside the engine is required to use
the engine through Its controls.

Since the details are hidden, inner working can be changed as


needed.
Stack class is practical implementation of encapsulation.
It is like stack of slates put on the table.

The first plate put on the table is the last plate to be used.

Stacks are controlled through 2 operations : push() and pop().

But for this implementation you don’t need to worry about the
detailing.

Stack example will be seen in practicals video.

You might also like