Download presentation
Presentation is loading. Please wait.
1
Introduction to Programming with Java, for Beginners Scope
2
1 Scope means the area of code in which an entity is known We will discuss the scope of a: Variable - what code can access it? Method - what code can call it? Sometimes scope is explicitly designated with a keyword private: known only within the class public: known outside of (and within) the class Other times it is implicitly designated by location e.g. method parameters are known only in the method in which they are defined
3
2 Instance Variables, Methods Recommendations Make all instance variables private Make most methods public Make a method private if it need/should only be called by methods in the same class A common scenario: We write a method that gets very long and/or complicated, so we want to break it in to subproblems Or, we have several methods that need to do some of the same subproblem We create a private “helper” method to handle the subproblem and let the other methods call it.
4
3 Method Parameters A method parameter is an “input variable” Scope: the method in which it is defined It “comes alive” when the method is entered It “dies” when the method is exited No other method can access (read/write) it
5
4 Local Variables A “local variable” is defined within a method body {} It may be defined in a block {} within a method body Scope: point of declaration to end of closest enclosing block We don’t use public/private for local variables. They are inherently private to the method in which they are defined
6
5 CodeNotes // Converts 0,1,2,3 to // “north”, “east”, “south”, “west” public String direction(int d){ String result = “unknown”; if (d == 0) result = "north"; else if (d == 1) result = "east"; else if (d == 2) result = ”south"; else if (d == 3) result = "west"; return result; } Method parameters (e.g. d) are only known within the method. Local variables (e.g. result), are known from the point of declaration until the end curly brace of the block in which they are declared. By contrast, instance variables are declared outside of any method and are known by all methods in the class in which they’re declared. Example
7
6 The “this” Keyword The keyword this means “this object”. It may be used to specify an instance variable public class Dot{ private int x; public void setX(int x){ this.x = x; // fixed!! } } public class Dot{ private int x; public void setX(int x){ x = x; // problem!! } }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.