classes and methods. classes class definition data fields –variables to store data items...
Post on 18-Jan-2016
217 Views
Preview:
TRANSCRIPT
Classes and Methods
Classes
data field 1
method n
data field n
method 1
An object
...
...
State
Behavior
Data Fieldradius = 5
MethodfindArea
A Circle object
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
Example
Circle
radius
findArea
circle1: Circle
radius = 2
new Circle()
circlen: Circle
radius = 5
new Circle()
...
Graphicalnotation forclasses
Graphicalnotation forobjects
Fields in Class Definition
• Class variables
• Instance variables
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.
Instance variables
• Variables associated with each object
• A separate value for each instance of a class
• For example, name , address etc.
Example
Class Sphere Definitionpublic class Sphere {// class variablestatic double PI=3.14;
// instance variablesdouble xCenter;double yCenter;double zCenter;double radius;}
Example
Methods in Class Definition
• Instance Methods
• Class Methods
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
Instance Methods
• Can execute when objects exist.
• Example: calculate area()
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();
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...}
Defining Methods
• Self contained block of codes
• Reusable
• Can be executed from anywhere in the program
• Calling a method
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
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
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
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;
}
Example
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;}
Passed by Value
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}}
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...}
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);
}
}
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;
}
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...
}
Using Initialization Blocks
• There are two kinds of initialization blocks:– static initialization block – non-static initialization block
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 }
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
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
LAB PRACTICE
• Compile & execute “TryInitialization” class with static initialization and non-static initialization block.
• Examine its output.
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
top related