Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Scope

100% developed
From Wikibooks, open books for an open world
<Java Programming

Object LifecycleJava Programming
Scope
Nested Classes
NavigateClasses and Objects topic:()


Scope

[edit |edit source]

The scope of a class, a variable or a method is its visibility and its accessibility. The visibility or accessibility means that you can use the item from a given place.

Scope of method parameters

[edit |edit source]

A method parameter is visible inside of the entire method but not visible outside the method.

Computer codeCode listing 3.14: Scope.java
publicclassScope{publicvoidmethod1(inti){i=i++;method2();intj=i*2;}publicvoidmethod2(){intk=20;}publicstaticvoidmain(String[]args){method1(10);}}

Incode listing 3.14,i is visible within the entiremethod1 method but not in themethod2 and themain methods.

Scope of local variables

[edit |edit source]

A local variable is visible after its declaration until the end of the block in which the local variable has been created.

ExampleCode section 3.50: Local variables.
{...// myNumber is NOT visible{// myNumber is NOT visibleintmyNumber;// myNumber is visible{...// myNumber is visible}// myNumber is visible}// myNumber is NOT visible...}

Access modifiers

[edit |edit source]

You surely would have noticed by now, the wordspublic,protected andprivate at the beginning of class's method declarations used in this book. These keywords are called theaccess modifiers in the Java language syntax, and they define the scope of a given item.

For a class

[edit |edit source]
  • If a class haspublic visibility, the class can be referenced by anywhere in the program.
  • If a class hasprotected visibility, the class can be referenced only in the package where the class is defined.
  • If a class hasprivate visibility, (it can happen only if the class is defined nested in another class) the class can be accessed only in the outer class.

For a variable

[edit |edit source]
  • If a variable is defined in apublic class and it haspublic visibility, the variable can be referenced anywhere in the application through the class it is defined in.
  • If a variable hasprotected visibility, the variable can be referenced only in the sub-classes and in the same package through the class it is defined in.
  • If a variable haspackage visibility, the variable can be referenced only in the same package through the class it is defined in.
  • If a variable hasprivate visibility, the variable can be accessed only in the class it is defined in.

For a method

[edit |edit source]
  • If a method is defined in apublic class and it haspublic visibility, the method can be called anywhere in the application through the class it is defined in.
  • If a method hasprotected visibility, the method can be called only in the sub-classes and in the same package through the class it is defined in.
  • If a method haspackage visibility, the method can be called only in the same package through the class it is defined in.
  • If a method hasprivate visibility, the method can be called only in the class it is defined in.

For an interface

[edit |edit source]

The interface methods and interfaces are alwayspublic. You do not need to specify the access modifier. It will default topublic. For clarity it is considered a good practice to put thepublic keyword.

The same way all member variables defined in the Interface by default will becomestaticfinal once inherited in a class.

Summary

[edit |edit source]
ClassNested classMethod, or Member variableInterfaceInterface method signature
publicvisible from anywheresame as its classsame as its classvisible from anywherevisible from anywhere
protectedN/Aits class and its subclassits class and its subclass, and from its packageN/AN/A
packageonly from its packageonly from its packageonly from its packageN/AN/A
privateN/Aonly from its classonly from its classN/AN/A

The cases in bold are the default.

Utility

[edit |edit source]

A general guideline for visibilities is to only make a member as visible as it needs to be. Don't make a member public if it only needs to be private.

Doing so, you can rewrite a class and change all the private members without making compilation errors, even you don't know all the classes that will use your class as long as you do not change the signature of the public members.

Field encapsulation

[edit |edit source]

Generally, it is best to make data private or protected. Access to the data is controlled bysetter andgetter methods. This lets the programmer control access to data, allowing him/her to check for and handle invalid data.

ExampleCode section 3.51: Encapsulation.
privateStringname;/** * This is a getter method because it accesses data from the object. */publicStringgetName(){returnname;}/** * This is a setter method because it changes data in the object. */publicbooleansetName(StringnewName){if(newName==null){returnfalse;}else{name=newName;returntrue;}}

In thecode section 3.51, thesetName() method will only change the value ofname if the new name is not null. BecausesetName() is conditionally changing name, it is wise to return a boolean to let the program know if the change was successful.

Test your knowledge

Question 3.15: Consider the following class.

Computer codeQuestion 3.15: Question15.java
publicclassQuestion15{publicstaticfinalintQKQKQKQK_MULTIPLIER=2;publicintijijijijijijijijijAwfulName=20;privateintunununununununununCrummyName=10;privatevoidmememememememeUglyName(inti){i=i++;tltltltltltltltltlBadName();intj=i*QKQKQKQK_MULTIPLIER;}publicvoidtltltltltltltltltlBadName(){intk=ijijijijijijijijijAwfulName;}publicstaticvoidmain(String[]args){mememememememeUglyName(unununununununununCrummyName);}}

List the fields and methods of this class that can be renamed without changing or even knowing the client classes.

Answer
  1. unununununununununCrummyName
  2. mememememememeUglyName()

Every field or method that is public can be directly called by a client class so this class would return a compile error if the field or the method has a new name.


Object LifecycleJava Programming
Scope
Nested Classes
Retrieved from "https://en.wikibooks.org/w/index.php?title=Java_Programming/Scope&oldid=3673870"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp