Presentation is loading. Please wait.

Presentation is loading. Please wait.

Variables and Their scope

Similar presentations


Presentation on theme: "Variables and Their scope"— Presentation transcript:

1 Variables and Their scope
All variables have a scope of existence The context in which they are accessible by a program The scope of a variable starts in the block of code in which it is declared, and propagates downward Similarly, different functions or subroutines at the same level have totally different scopes! But may both inherit access to class-wide variables { int a; a = 10; { int b; b = a; // a comes from the // higher block } a = b + 2; // error! }

2 Function Parameters For basic data types (boolean, int, double, etc.), when you pass data to a function or subroutine, the function actually gets a copy of the argument, under a different name public static int square(int x){ int s = x * x; return s; }

3 Function parameters A consequence of the above is that if you modify a function parameter, it is not reflected in the original copy public static void square(int x){ x = x * x; } square(a); // the value inside a does not get changed!

4 Objects Review: difference between static and non- static (aka dynamic)? Binding/Scope Review: Instance methods? How are the called? Instance variables? How are they accessed? Static methods: How are they called? Static variables:

5 Object allocation Walk through “memory on paper” example.
class Inventory{ public String name; public int quantity; public double price; } The command “new Inventory()” allocates space for all three attributes, and gives them one name of the whole object

6 Object Usage Recall: objects are all by reference, meaning any subroutine that uses them as parameters has access to the actual objects, instead of a copy. Now, if we pass an object to a function, and that function makes a change to the data inside, it will affect the original! Can be good or bad, but has to be remembered

7 Object methods When you call a function that is a member of an object, that function has in its scope (in addition to any locally defined variables): Its parameters The instance variables of the parent object The (static) class variables of the parent object’s class Example: Student class with auto-populated ID’s


Download ppt "Variables and Their scope"

Similar presentations


Ads by Google