VARIABLES AND THEIR SCOPE All variables have a
VARIABLES AND THEIR SCOPE • All variables have a scope of existence { int a; a = 10; • 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 { int b; b = a; // a comes from the // higher block • Similarly, different functions or subroutines at the same level have totally different scopes! • But may both inherit access to class-wide variables } a = b + 2; // error! }
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; }
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!
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: • How are they accessed?
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
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
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
- Slides: 7