Presentation is loading. Please wait.

Presentation is loading. Please wait.

Summary of the lecture We discussed –variable scope –instance variable declarations –variable lifetime.

Similar presentations


Presentation on theme: "Summary of the lecture We discussed –variable scope –instance variable declarations –variable lifetime."— Presentation transcript:

1 Summary of the lecture We discussed –variable scope –instance variable declarations –variable lifetime

2 Variable scope The scope of a variable is the part of a program where a variable declaration is in effect. Variables declared in different ways have different scope.

3 Local variables A variable declared within a method is a local variable. The scope of a local variable is from the point of the declaration to the end of the method body.

4 Issue #1 Using a variable in many methods It is often necessary to refer to a variable from many methods in a class. A local variable cannot be used outside of the method in which it is declared.

5 Instance variables A variable declared as a class member (i.e. within the class body but not within any method) is called an instance variable. The scope of an instance variable is the entire class body. Each instance of a class has its own set of instance variables.

6 Instance variable declaration An instance variable declaration consists of an access control modifier in addition to a type and a name. A rule in CSE115 is that all instance variables must be declared using the “private” access control modifier

7 Access Control Modifiers “public” – the member can be accessed from outside the class “private” – the member can be access only from inside the class

8 Class members: (instance) methods & instance variables Any class member (method or variable declared in the class body, but not inside a method) must have an access control modifier. Our rule: methods are public, instance variables are private. Later in semester we will justify this rule (one we know a little more about the issues involved)

9 Lifetime In addition to scope, variables have another important property called lifetime. The lifetime of a variable is the time during execution of a program that the variable exists.

10 Lifetime of a local variable A local variable comes into existence when a method is called, and disappears when the method is completed.

11 Lifetime of an instance variable Instance variables are created when a class is instantiated. Each object has its own set of instance variables. Instance variables persist as long as their objects persist –as far as we know right now, objects persist until the end of the runtime of the program.


Download ppt "Summary of the lecture We discussed –variable scope –instance variable declarations –variable lifetime."

Similar presentations


Ads by Google