0% found this document useful (0 votes)
2 views15 pages

Module 2 Half

This document introduces the concept of classes in Java, explaining that a class is a blueprint for creating objects, defining their properties and behaviors. It covers class fundamentals, object instantiation, method creation, and the use of constructors for initializing objects. Additionally, it discusses the relationship between objects and their reference variables, as well as how to define and use methods with parameters.

Uploaded by

shivapur.cs
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)
2 views15 pages

Module 2 Half

This document introduces the concept of classes in Java, explaining that a class is a blueprint for creating objects, defining their properties and behaviors. It covers class fundamentals, object instantiation, method creation, and the use of constructors for initializing objects. Additionally, it discusses the relationship between objects and their reference variables, as well as how to define and use methods with parameters.

Uploaded by

shivapur.cs
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/ 15

Module 2

Introducing Classes

 The class is at the core of Java.


 It is the logical construct upon which the en re Java language is built because it defines the
shape and nature of an object.

Class Fundamentals
 Class defines a new data type. Once defined, this new type can be used to create objects of that
type.
 Thus, a class is a template for an object, and an object is an instance of a class. Because an object
is an instance of a class, you will o en see the two words object and instance used
interchangeably.

The General Form of a Class


 When you define a class, you declare its exact form and nature. You do this by specifying the
data that it contains and the code that operates on that data.
 A class is declared by use of the class keyword

SYNTAX
class classname {

type instance-variable1;

type instance-variable2;

// ...

type instance-variableN;

type methodname1(parameter-list) {

// body of method

type methodnameN(parameter-list) {

// body of method

Dept of CSE
HKBK College Of Engineering
 The data, or variables, defined within a class are called instance variables.
 The code is contained within methods.
 Collec vely, the methods and variables defined within a class are called members of the class.
 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.
 Thus, the data for one object is separate and unique from the data for another.

A Simple Class
Here is a class called Box that defines three instance variables: width, height, and depth

class Box {

double width;

double height;

double depth;

 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.
 It is important to remember that a class declara on only creates a template; it does not
 create an actual object

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

 A er this statement executes, mybox will be an instance of Box.


 Thus, it will have “physical” reality.
 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;

Dept of CSE
HKBK College Of Engineering
class Box {

double width;

double height;

double depth;

// This class declares an object of type Box.

class BoxDemo {

public sta c 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);

Declaring Objects

 When you create a class, you are crea ng a new data type.
 However, obtaining objects of a class is a two-step process.
 First, you must 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 me) memory for an object and
returns a reference to it.
 This reference is, more or less, the address in memory of the object allocated by new. This
reference is then stored in the variable.
 Thus, in Java, all class objects must be dynamically allocated.

Box mybox = new Box();

Dept of CSE
HKBK College Of Engineering
 This statement combines the two steps just described. It can be rewri en like this to show each
step more clearly:

Box mybox; // declare reference to object

mybox = new Box(); // allocate a Box object

 The first line declares mybox as a reference to an object of type Box.


 A er this line executes, mybox contains the value null, which indicates that it does not yet point
to an actual object.
 Any a empt to use mybox at this point will result in a compile- me error. The next line allocates
an actual object and assigns a reference to it to mybox.
 A er the second line executes, you can use mybox as if it were a Box object. But in reality, mybox
simply holds the memory address of the actual Box object.

 Here, class-var is a variable of the class type being created. The classname is the name of the
class that is being instan ated.
 The class name followed by parentheses specifies the constructor for the class.
 A constructor defines what occurs when an object of a class is created.
 Constructors are an important part of all classes and have many significant a ributes.
 It is important to understand that new allocates memory for an object during run me.
 The advantage of this approach is that your program can create as many or as few objects as it
needs during the execu on of your program.
 However, since memory is finite, it is possible that new will not be able to allocate memory for
an object because insufficient memory exists.
 If this happens, a run- me excep on will occur.
 A class creates a new data type that can be used to create objects.
 That is, a class creates a logical framework that defines the rela onship between its members.
When you declare an object of a class, you are crea ng an instance of that class.
 Thus, a class is a logical construct. An object has physical reality.

Dept of CSE
HKBK College Of Engineering
Assigning Object Reference Variables
Object reference variables act differently when an assignment takes place.

Box b1 = new Box();

Box b2 = b1;

 A er this fragment executes, b1 and b2 will both refer to the same object.
 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.
 Thus, any changes made to the object through b2 will affect the object to which b1 is referring,
since they are the same object.
 Although b1 and b2 both refer to the same object, they are not linked in any other way.

Box b1 = new Box(); Box b2 = b1;

// ...

b1 = null;

Here, b1 has been set to null, but b2 s ll points to the original object.

Dept of CSE
HKBK College Of Engineering
Introducing methods
This is the general form of a method:

type name(parameter-list) {

// body of method

 Here, type specifies the type of data returned by the method. This can be any valid type,
including class types that you create.
 If the method does not return a value, its return type must be void.
 The name of the method is specified by name. This can be any legal iden fier other than those
already used by other items within the current scope.
 The parameter-list is a sequence of type and iden fier pairs separated by commas. Parameters
are essen ally 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 rou ne using the
following form of the return statement:

return value;

 Here, value is the value returned.

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

class BoxDemo3 {

public sta c void main(String args[]) {

Dept of CSE
HKBK College Of Engineering
Box mybox1 = new Box();

// assign values to mybox1's instance variables

mybox1.width = 10;

mybox1.height = 20;

mybox1.depth = 15;

// display volume of first box

mybox1.volume();

This program generates the following output, which is the same as the previous version.

Volume is 3000.0

Volume is 162.0

Look closely at the following two lines of code:

mybox1.volume();

 The first line here invokes the volume( ) method on mybox1.


 That is, it calls volume( ) rela ve to the mybox1 object, using the object’s name followed
by the dot operator.
 Thus, the call to mybox1.volume( ) displays the volume of the box defined by mybox1,
 There is something very important to no ce inside the volume( ) method: the instance
variables width, height, and depth are referred to directly, without preceding them with
an object name or the dot operator.
 When a method uses an instance variable that is defined by its class, it does so directly,
without explicit reference to an object and without use of the dot operator.
 This is easy to understand if you think about it. A method is always invoked rela ve to
some object of its class. Once this invoca on has occurred, the object is known.

Returning a Value
While the implementa on of volume( ) does move the computa on of a box’s volume

inside the Box class where it belongs, it is not the best way to do it.

class Box {

double width;

Dept of CSE
HKBK College Of Engineering
double height;

double depth;

// compute and return volume

double volume() {

return width * height * depth;

class BoxDemo4 {

public sta c void main(String args[]) {

Box mybox1 = new Box();

double vol;

// assign values to mybox1's instance variables

mybox1.width = 10;

mybox1.height = 20;

mybox1.depth = 15;

// get volume of first box

vol = mybox1.volume();

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

 As you can see, when volume( ) is called, it is put on the right side of an assignment statement.
 On the le is a variable, in this case vol, that will receive the value returned by volume( ).
 Thus, a er vol = mybox1.volume(); executes, the value of mybox1.volume( ) is 3,000 and this
value then is stored in vol.

There are two important things to understand about returning values:

 The type of data returned by a method must be compa ble with the return type specified by the
method. For example, if the return type of some method is boolean, you could not return an
integer.
 The variable receiving the value returned by a method (such as vol, in this case) must also be
compa ble with the return type specified for the method.

Adding a Method That Takes Parameters


 While some methods don’t need parameters, most do. Parameters allow a method to be
generalized.

Dept of CSE
HKBK College Of Engineering
 That is, a parameterized method can operate on a variety of data and/or be used in a number of
slightly different situa ons

int square()

return 10 * 10;

 While this method does, indeed, return the value of 10 squared, its use is very limited.
 However, if you modify the method so that it takes a parameter, as shown next, then you can
make square( ) much more useful.

int square(int i)

return i * i;

 Now, square( ) will return the square of whatever value it is called with. That is, square( ) is now a
general-purpose method that can compute the square of any integer value, rather than just 10.

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

 In the first call to square( ), the value 5 will be passed into parameter i.
 In the second call, I will receive the value 9.
 The third invoca on passes the value of y, which is 2 in this example.
 As these examples show, square( ) is able to return the square of whatever data it is
passed
 A parameter is a variable defined by a method that receives a value when the method is
called. For example, in square( ), i is a parameter.
 An argument is a value that is passed to a method when it is Invoked.
 For example, square(100) passes 100 as an argument. Inside square( ), the parameter i
receives that value.

Dept of CSE
HKBK College Of Engineering
 Thus, a be er approach to se ng the dimensions of a box is to create a method that
takes the dimensions of a box in its parameters and sets each instance variable
appropriately.
 This concept is implemented by the following program:

// This program uses a parameterized method.

class Box {

double width;

double height;

double depth;

// compute and return volume

double volume() {

return width * height * depth;

// sets dimensions of box

void setDim(double w, double h, double d) {

width = w;

height = h;

depth = d;

class BoxDemo5 {

public sta c void main(String args[]) {

Box mybox1 = new Box();

Box mybox2 = new Box();

double vol;

// ini alize each box

mybox1.setDim(10, 20, 15);

mybox2.setDim(3, 6, 9);

// get volume of first box

vol = mybox1.volume();

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

Dept of CSE
HKBK College Of Engineering
// get volume of second box

vol = mybox2.volume();

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

}}

 As you can see, the setDim( ) method is used to set the dimensions of each box. For example,
when mybox1.setDim(10, 20, 15); is executed, 10 is copied into parameter w, 20 is copied
into h, and 15 is copied into d.
 Inside setDim( ) the values of w, h, and d are then assigned to width, height, and depth,
respec vely.

Constructors
 It can be tedious to ini alize all of the variables in a class each me an instance is
created.
 Even when you add convenience func ons like setDim( ), it would be simpler and more
concise to have all of the setup done at the me the object is first created.
 Because the requirement for ini aliza on is so common, Java allows objects to ini alize
themselves when they are created.
 This automa c ini aliza on is performed through the use of a constructor.
 A constructor ini alizes an object immediately upon crea on.
 It has the same name as the class in which it resides and is syntac cally similar to a
method.
 Once defined, the constructor is automa cally called immediately a er the object is
created, before the new operator completes.
 Constructors look a li le strange because they 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 ini alize the internal state of an object so that the code
crea ng an instance will have a fully ini alized, usable object immediately.

class Box {

double width;

double height;

double depth;

// This is the constructor for Box.

Box() {

System.out.println("Construc ng Box");

width = 10;

Dept of CSE
HKBK College Of Engineering
height = 10;

depth = 10;

// compute and return volume

double volume() {

return width * height * depth;

class BoxDemo6 {

public sta c void main(String args[]) {

// declare, allocate, and ini alize 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);

When this program is run, it generates the following results:

Construc ng Box

Construc ng Box

Volume is 1000.0

Volume is 1000.0

class-var = new classname( );

 Now you can understand why the parentheses are needed a er the class name. What is
actually happening is that the constructor for the class is being called. Thus, in the line
Box mybox1 = new Box();

Dept of CSE
HKBK College Of Engineering
 new Box( ) is calling the Box( ) constructor new .
 When you do not explicitly define a constructor for a class, then Java creates a default
constructor for the class

Parameterized Constructors

 While the Box( ) constructor in the preceding example does ini alize 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 solu on is to add parameters to the constructor

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;

class BoxDemo7 {

public sta c void main(String args[]) {

// declare, allocate, and ini alize Box objects

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

Box mybox2 = new Box(3, 6, 9);

Dept of CSE
HKBK College Of Engineering
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);

The output from this program is shown here:

Volume is 3000.0

Volume is 162.0

The this keyword


 Some mes 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

Box(double w, double h, double d) {

this.width = w;

this.height = h;

this.depth = d;

Uses of this:

 To overcome shadowing or instance variable hiding.


 To call an overload constructor

Instance Variable Hiding


 It is illegal in Java to declare two local variables with the same name inside the same or
enclosing scopes.
 Interes ngly, you can have local variables, including formal parameters to methods, which
overlap with the names of the class’ instance variables.
 However, 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) {

Dept of CSE
HKBK College Of Engineering
this.width = width;

this.height = height;

this.depth = depth;

NOTE: The use of this in such a context can some mes be confusing, and some

programmers are careful not to use local variables and formal parameter names that hide

instance variables.

Garbage Collec on
 Since objects are dynamically allocated by using the new operator, you might be
wondering how such objects are destroyed and their memory released for later
realloca on.
 Java takes a different approach; it handles dealloca on for you automa cally.
 The technique that accomplishes this is called garbage collec on.
 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 collec on only occurs sporadically (if at all) during the execu on of your
program.
 It will not occur simply because one or more objects exist that are no longer used.

Dept of CSE
HKBK College Of Engineering

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy