11.3 Scope
So in the previous video, we learned what the packages were and how to use them. Now, let’s take a look at the scope of the variable. In programming, a variable can be declared and defined in a class, method or block. It defines the scope of the variable, that is, the visibility or accessibility of a variable. Variables declared within a block or method are not visible from the outside. If we try to do this, we will get a compilation error. Note that the scope of a variable can be nested. We can report variables anywhere in the program, but it is limited in scope. A variable can be a parameter of a method or a constructor. The variable declared in the main function is not accessible outside the main() function So we’ll start by creating a new class and we’ll just call it ScopeCheck Is what we’re going to do is create a few variables first So, public int publicVar equals 0 and a private variable also So, it will be private private var = 1. Then we will add a constructor without parameter. And inside, we’ll just make a message to say "the scope check has been created" and then simply show the values of the variables So, public var is equal + public var And private var is equal to private var. We will also create a getter and this getter will be just for the privateVar. So what we’re going to do now is go into the hand class. create a new instance, then check the privateVar value in main. And here in the main method we will do String privateVar. Yes, it is the same variable name as in the ScopeCheck class So that equals "This is private to the main() class" Then we will create an instance of ScopeCheck. So ScopeCheck scope = new ScopeCheck And we’ll just messag us two privateVar variables So, that of ScopeCheck and the main class. the privateVar staff instance is " Scope.getPrivateVar And then we will also display our string value. So, if we actually execute this. As we can see, we do have our value 1 And our string message. But why the two values are displayed differently then that have the same variable name In fact whatever we refer to privateVar, Java takes into account the one declared in the hand Because it is the only one available in the current scope. That was it for part 1 of the variable scope In the next video, we’ll see part 2 Go, I’ll see you next!