Classes and Methods. Classes Class Definition Data Fields –Variables to store data items...

33
Classes and Methods

Transcript of Classes and Methods. Classes Class Definition Data Fields –Variables to store data items...

Page 1: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Classes and Methods

Page 2: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Classes

data field 1

method n

data field n

method 1

An object

...

...

State

Behavior

Data Fieldradius = 5

MethodfindArea

A Circle object

Page 3: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Class Definition

• Data Fields– Variables to store data items– Differentiate multiple objects of a class– They are called data members

• Methods– Operations of a class– They operate on variables of the class

Page 4: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Example

Circle

radius

findArea

circle1: Circle

radius = 2

new Circle()

circlen: Circle

radius = 5

new Circle()

...

Graphicalnotation forclasses

Graphicalnotation forobjects

Page 5: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Fields in Class Definition

• Class variables

• Instance variables

Page 6: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Fields in Class Definition

• Class Variable– Only one copy is shared with all the objects of

the class– Shared among all objects of a class– Exists even if no object has been created– Also called as static fields– Declared using the keyword static– If value is changed, it is reflected for all

objects.

Page 7: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Instance variables

• Variables associated with each object

• A separate value for each instance of a class

• For example, name , address etc.

Page 8: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Example

Class Sphere Definitionpublic class Sphere {// class variablestatic double PI=3.14;

// instance variablesdouble xCenter;double yCenter;double zCenter;double radius;}

Page 9: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Example

Page 10: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Methods in Class Definition

• Instance Methods

• Class Methods

Page 11: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Class Methods

• Execute class methods even when no objects of a class exist

• Declared using the keyword static.

• Static methods

• Can not refer to an instance variable

• Example: main method

• Buildin methods in standard class Math

Page 12: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Instance Methods

• Can execute when objects exist.

• Example: calculate area()

Page 13: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Accessing Variables and Methods

• Accessing Class Methods– double rootPi = Math.sqrt(Math.PI);– Objects can also access in the same way

• Instance variables and methods– double ballVolume = ball.volume();

Page 14: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Defining Classes

class Sphere {static final double PI = 3.14; //class variable with fixed valuestatic int count = 0; // Class variable to count objects

// Instance variablesdouble radius; // Radius of a spheredouble xCenter; // 3D coordinatesdouble yCenter; // of the centerdouble zCenter; // of a sphere// Plus the rest of the class definition...}

Page 15: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Defining Methods

• Self contained block of codes

• Reusable

• Can be executed from anywhere in the program

• Calling a method

Page 16: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Basic Structure of a method

return_type methodName( arg1, arg2, ..., argn )

{ code here

}

• Return Statement

return return_value; // To return a value from a method

Page 17: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Example

public static int max(int num1, int num2){

int result = 0;

if (num1 > num2) result = num1;else result = num2;

return result;}

modifier

returnValueType

methodName

parameters

return value

methodbody

methodheading

Page 18: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Parameters and Arguments

• Parameter– has a name and a type– Appear in definition of the method– Defines type of value to be passed to method when

called

• Arguments– Actual value that is passed to a method when

executed– Must be consistent with the type specified in

parameter definition

Page 19: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Example

public static void main(String[] args){

...

x = obj.mean( 3.0 , 5.0 );

}

double mean( double value1 , double value2 ){

double result = ( value1 + value2 )/ 2.0;

return result;

}

Page 20: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Example

Page 21: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Passed by Value

double d = 2.0;changeMe(d);System.out.println(d);

public void changeMe(double d){     //this has no effect on d outside of this method!     d = 345.0;}

Page 22: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Passed by Value

Page 23: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Class Method Definition

class Sphere {// Class definition as before...// Static method to report the number of

objects createdstatic int getCount() {return count; // Return current object count}}

Page 24: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Example Classclass Sphere {static final double PI = 3.14; // Class variable that has a fixed valuestatic int count = 0; // Class variable to count objects// Instance variablesdouble radius;double xCenter; // 3D coordinatesdouble yCenter; // of the centerdouble zCenter; // of a sphere// Static method to report the number of objects createdstatic int getCount(){return count; // Return current object count}// Instance method to calculate volumedouble volume() {return 4.0/3.0*PI*radius*radius*radius;}// Plus the rest of the class definition...}

Page 25: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

class Sphere {static final double PI = 3.14; static int count = 0;

// Instance variablesdouble radius = 5.0; double xCenter = 10.0; double yCenter = 10.0; double zCenter = 10.0;

// Static method to report the number of objects createdstatic int getCount(){

return count; // Return current object count

}

// Instance method to calculate volume

double volume() {return 4.0/3.0*PI*radius*radius*radius;

}// Plus the rest of the class definition...

public static void main (String[] args){int count; double volume; count=Sphere.getCount();System.out.println(count);Sphere s1=new Sphere();volume=s1.volume();System.out.println(volume);

}

}

Page 26: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

The Variable this

• Every instance method has a variable with the name this that refers to the current object for which the method is being called

void changeRadius(double radius) {// Change the instance variable to the argument valuethis.radius = radius;

}

Page 27: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Initializing data members: The ordinary way

class Sphere {static final double PI = 3.14; // Class variable that has a fixed valuestatic int count = 0; // Class variable to count objects// Instance variablesdouble radius = 5.0; // Radius of a spheredouble xCenter = 10.0; // 3D coordinatesdouble yCenter = 10.0; // of the centerdouble zCenter = 10.0; // of a sphere// Rest of the class...

}

Page 28: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Using Initialization Blocks

• There are two kinds of initialization blocks:– static initialization block – non-static initialization block

Page 29: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

static initialization block

• A static initialization block is a block defined using the keyword static and is executed once when the class is loaded.

• A static initialization block can initialize only static data members of the class.

• A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword.

• Here is an example: static { // whatever code is needed for initialization goes here }

Page 30: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

static initialization

block

class TryInitialization { static int[] values = new int[10]; static {System.out.println("Running initialization

block.");for(int i=0; i<values.length; i++) {values[i] = (int)(100.0*Math.random());}}// List values in the array for an objectvoid listValues() {System.out.println(); // Start a new linefor(int value : values) {System.out.print(" " + value); // Display values}System.out.println(); // Start a new line}public static void main(String[] args) {TryInitialization example = new

TryInitialization();System.out.println("\nFirst object:");example.listValues();example = new TryInitialization();System.out.println("\nSecond object:");example.listValues();}}

Running initialization block.First object:40 97 88 63 58 48 84 5 32 67Second object:40 97 88 63 58 48 84 5 32 67

Page 31: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

Non-static initialization block

– non-static initialization block is executed for each object that is created and thus can initialize instance variables in a class.

– This block appears without the static keyword.

{ // whatever code is needed for initialization goes here } Running initialization block.

First object:66 17 98 59 99 18 40 96 40 21Running initialization block.Second object:57 86 79 31 75 99 51 5 31 44

Page 32: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

LAB PRACTICE

• Compile & execute “TryInitialization” class with static initialization and non-static initialization block.

• Examine its output.

Page 33: Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.

LAB PRACTICE

• Make a class Bicycle, identify its data members for example “speed=0”, “gear=1” etc.

• Add methods like changeGear(int), speedUp(int) , applyBrakes(),

printStates() etc. Make a main method to create 2 bicycle objects and call functions of the class in the following sequence.

1. Change speed2. Change gear3. Print states4. Apply brakes5. Print states