1 / 11

Methods, Parameters, and Scope

Methods, Parameters, and Scope. Contents. Java classes -- encapsulation of data and operations upon it Example Visibility -- scope of variables Parameter passing Review of class properties When to declare a feature public. object1. public class Exampl { //public data

vail
Download Presentation

Methods, Parameters, and Scope

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Methods, Parameters, and Scope Contents Java classes -- encapsulation of data and operations upon it Example Visibility -- scope of variables Parameter passing Review of class properties When to declare a feature public

  2. object1 public class Exampl { //public data // private data // public methods // private methods } object2 Java Classes A class contains data and the operations performed upon the data. Operations are called methods. Methods may initialize data members of the class, transform data members of the class, or observe (return) the current value of a data member. A class is a prototype for constructing objects. Examplobject1 = new Exampl(initialization parameters); object2

  3. private data members private class data member constructor using default initial values constructor with user provided initial values method that transforms a data member (void--no return) methods that observe, but do not change, the value of a data member. public static methods may be accessed without first creating an instance of the class (object) Java Classes public class Dog { private int xpos, ypos; private String bark; private static int numDogs = 0; public Dog( ) { xpos = 0; ypos = 0; numDogs++; bark = “Bow Wow”; } public Dog(int x, int y, String says) { xpos = x; ypos = y; bark = says; numDogs++; } public void moveTo(int x, int y) { xpos = x; ypos = y; } public int getX( ){ return xpos;} public int getY( ){ return ypos;} public String hearDog( ) { return bark;} public static int countDogs( ) { return numDogs;} } Static data members are common to a class and are not unique for each individual object. Only static data may be initialized directly upon declaration in a class definition. Each object maintains its own data. Private data is accessible only to methods of class Dog.

  4. class header Lassie : Dog Each individual object will hold its own copy of this data. Privately declared data members are accessible only to methods of the class. name of class 10 Visibility modifier 25 class declaration The value of this data member is held uniquely by the class. Since it is private, it too is accessible only to methods of the class. Only data declared as static may be initialized in the declaration! Ruff, ruff Constructors are declared with visibility => public. Constructors have no return type and use the name of the class. Constructors initialize the data members of the class. return type (none) method name parameter list method header method body accessible from the class Java Classes Declare an instance of class Dog Dog Lassie = new Dog(10, 25, “Ruff, ruff”); public class Dog { private int xpos, ypos; private String bark; private static int numDogs= 0; int xpos int ypos String bark int numDogs Dog ( ) Dog (int x, int y, String says) void moveTo (int x, int y) int getX( ) int getY( ) int countDogs( ) public Dog( ) {….} public Dog(int x, int y, String says) {…..} public void moveTo(int x, int y) {..} public int getX( ) {return xpos;} ……. objects hold references to instructions for implementing methods Objects hold their own copies of data values If no constructor is provided, class data members are all initialized to 0 Reference to address of static data member public static int CountDogs( ) {…} }

  5. Visibility public class VisibilityDemo{ private intclassVar1; private intclassVar2; public int method1(int x) { intlocal = 0; for(inti = 0; i <x; i++) local +=i; returnlocal; } public voidmethod2( int x) { classVar1 = x + 10; classVar2 = method1(classVar2); } } The blue identifiers denote class variabes and methods. They have visibility anywhere inside the outermost pair of blue curly brackets The gray identifiers are local to a single block (identified by gray brackets). They are not visible to anything outside of their block, but are visible inside blocks nested inside of the gray bracketed block. The red identifiers are found inside the for-loop. The red variable i is visible only inside the loop. Parameters are denoted by green. They are visible everywhere inside the method in which they appear, but only in that method

  6. Visible inside and outside of all blocks Visible everywhere inside first outer block Visible everywhere inside second outer block Visible only inside nested for-loop Visibility The following code fragments contain situations that illustrate visibility rules. int sum = 0, total = 0; for (int inx = 0; inx < max; inx++) { total += sum; for (int j = 0; j < max; j++) { sum += j; } } sum = 0; for (int inx = 0; inx < max; inx++) { sum += inx; } { int x = 10, y = 20; x += y; {int x, z = 5; x = y + z; System.out.println(“inner block -- x = “+x); y = x; } System.out.println(“outer block -- x = “+x+”, y = “ + y); } inner block -- x = 25 outer block -- x = 30, y = 25 Variable y is visible in both the outer and inner blocks.. The identifier x is reused inside the inner block -- the inner and outer x refer to different variables.

  7. Visibility The same identifier may be reused for method names within the same class as long as the parameter list is different each time. public class Demo { public int myMethod(int param1) {…} public double myMethod (double param1) {…} public int myMethod (int param1, String param2) {…} } It is not acceptable (allowed) to use the same method identifier and parameter list with different return types public int myMethod(int param1) {…} public double myMethod(int param1) {…}

  8. Parameters Calling method Called methods 24 classVar myInt str myString public class ParamPassDemo { private int classVar; private String str; public ParamPassDemo( int x){ classVar = x; str = null; } public void set(int x) {x = x + 5; {classVar=x;} publicint get( ) {return classVar;} publicvoid setStr(String s) {str = s;} } public class Application { public static void main(String[] a) { int myInt = 24; String myString = “hello”; ParamPassDemo ppd =new ParamPassDemo(3); 29 ppd.setStr(myString) ppd.set(myInt); 29 Only a copy of the original is passed 3 24 value of ref. to String object null hello

  9. Things to remember Parameter passing When the parameter is a primitive type (int, boolean, double, etc.), only a copy of the associated value is passed. Changes to the copy made inside the method have no effect upon the original. When the parameter is an object (such as String), the value of the address of the object (a reference to it) is passed. The method receiving this parameter has the same access to the objects methods as any other client. Classes and methods A class encapsulates data with the operations that are to be performed upon it. The programmer can restrict or permit the user’s access to data members by declaring the features of the class (data attributes and methods) as private or public. An object-oriented program utilizes a collection of classes. A main function (method) must appear in one and only one of the classes that comprise a Java program.

  10. More things to remember Features with static scope Methods and data attributes declared as static are “maintained” by the class itself. One does not have to create an instance of the class (an object) inorder to access the static features that are public. Static methods may only refer to static variables. Static features are particularly useful for utility classes like Math and wrapper classes like Integer that are part of the standard Java library. For example -- statements such as: Math.sqrt(x); double x = Double.parseDouble(str);

  11. Public vs. Private When designing a class, the programmer must determine the visibility of the methods and data attributes (class variables). Here are some general guidelines for making the appropriate choice. Constructors should always be public Variables should be declared as private. If the user needs to view or change the value of a variable, get and set methods should be provided in the class. Constants should generally be private. Constants cannot be changed by a client, but are usually of little use outside of the class in which they are declared. The exception is well-known constants such as pi or e, the base for exponential functions, which may be made public for use by a client (and are in the Java library). Methods are usually public. Only methods used internally to compute an intermediate result should be declared as private.

More Related