📄 java2.txt
字号:
Day 15
Modifiers, Access Control, and Class Design
by Laura Lemay and Charles L. Perkins
CONTENTS
* Modifiers
* Controlling Access to Methods and Variables
* Why Access Control Is Important
* The Four Ps of Protection
* Method Protection and Inheritance
* Instance Variable Protection and Accessor Methods
* Class Variables and Methods
* Finalizing Classes, Methods, and Variables
* Finalizing Classes
* Finalizing Variables
* Finalizing Methods
* Abstract Classes and Methods
* Summary
* Q&A
Here at the start of Week 3, you've probably grasped the basics
of the Java language from Week 1, and you've applied them fairly
often to create applets in Week 2. You can stop here, if you
like, and go on your merry way, knowing enough Java to get by.
Week 3 extends what you already know. In this week you'll learn
more about advanced Java concepts such as access control and
packages, and you'll learn techniques for structuring large
programs in an efficient object-oriented way so your code can be
more easily maintained and extended or, if you so choose, easily
reused by other people.
Today we'll start with advanced Java language concepts for
organizing and designing individual classes:
* What a modifier is and how it's used
* Controlling access to methods and variables from outside a
class to better encapsulate your code
* Using a special case of controlling access to methods and
variables: instance variable accessor methods
* Using Class variables and methods to store class-specific
attributes and behavior
* Finalizing classes, methods, and variables so their values
or definitions cannot be subclasses or overridden
* Creating abstract classes and methods for factoring common
behavior into superclasses
Modifiers
The techniques for programming you'll learn today involve
different strategies and ways of thinking about how a class is
organized. But the one thing all these techniques have in common
is that they all use special modifier keywords in the Java
language.
In Week 1 you learned how to define classes, methods, and
variables in Java. Modifiers are keywords you add to those
definitions to change their meaning. Classes, methods, and
variables with modifiers are still classes, methods, and
variables, but the modifiers change their behavior or how Java
treats those elements.
Modifiers are special language keywords that modify the
definition (and the behavior) of a class, method, or variable.
Note
You've already learned about a few of these modifiers
earlier in the book, but here we'll talk about them in
detail so you can get the bigger picture of why modifiers
work the way they do.
The Java language has a wide variety of modifiers, including
* Modifiers for controlling access to a class, method, or
variable: public, protected, and private
* The static modifier for creating class methods and variables
* The abstract modifier, for creating abstract classes and
methods
* The final modifier, for finalizing the implementations of
classes, methods, and variables
* The synchronized and volatile modifiers, which are used for
threads and which you'll learn more about on Day 18,
"Multithreading"
* The native modifier, which is used for creating native
methods, which you'll learn about on Day 21, "Under the
Hood"
Some modifiers, as you can see, can apply only to classes and
methods or only to methods and variables. For each of the
modifiers, however, to use them you put them just previous to
the class, method, or variable definition, as in the following
examples:
public class MyApplet extends Java.applet.Applet { ... }
private boolean engineState;
static final double pi = 3.141559265
protected static final int MAXNUMELEMENTS = 128;
public static void main(String args[]) { ...}
The order of modifiers is irrelevant to their meaning-your order
can vary and is really a matter of taste. Pick a style and then
be consistent with it throughout all your classes. Here is the
usual order:
<access> static abstract synchronized volatile final native
In this definition, <access> can be public, protected, or
private (but no more than one of them).
All the modifiers are essentially optional; none have to appear
in a declaration. Good object-oriented programming style,
however, suggests adding as many as are needed to best describe
the intended use of, and restrictions on, the thing you're
declaring. In some special situations (inside an interface, for
example, as described tomorrow), certain modifiers are
implicitly defined for you, and you needn't type them-they will
be assumed to be there.
Controlling Access to Methods and Variables
The most important modifiers in the language, from the
standpoint of class and object design, are those that allow you
to control the visibility of, and access to, variables and
methods inside your classes.
Why Access Control Is Important
Why would you care about controlling access to methods and
variables inside your classes? If you remember way back to the
beginning of this book, I used the analogy of the pc-how you can
buy different pc components and put them all together so that
they interact to create a larger system.
Each component in that pc system works in a particular way and
has a specific way of interacting with the other components in
the system. For example, a video card plugs into your
motherboard using a standard socket and plug arrangement, as
does your monitor to the back of the card. And then your
computer can talk the right software language through the card
to get bits up on the screen.
The video card itself has a whole lot of other internal features
and capabilities beyond this basic hardware and software
interface. But as a user or consumer of the card, I don't need
to know what every single chip does, nor do I need to touch them
in order to get the card to work. Given the standard interfaces,
the card figures everything out and does what it needs to do
internally. And, in fact, the manufacturer of the card most
likely doesn't want me to go in and start mucking with
individual chips or capabilities of the card, because I'm likely
to screw something up. It's best if I just stick to the defined
interface and let the internal workings stay hidden.
Classes and objects are the same way. While a class may define
lots of methods and variables, not all of them are useful to a
consumer of that class, and some may even be harmful if they're
not used in the way they were intended to be used.
Access control is about controlling visibility. When a method or
variable is visible to another class, its methods can reference
(call, or modify) that method or variable. Protecting those
methods and instance variables limits the visibility and the use
of those methods and variables (and also limits what you have to
document!). As a designer of a class or an entire hierarchy of
classes, therefore, it's a good idea to define what the external
appearance of a class is going to be, which variables and
methods will be accessible for other users of that class, and
which ones are for internal use only. This is called
encapsulation and is an important feature of object-oriented
design.
Encapsulation is the process of hiding the internal parts of an
object's implementation and allowing access to that object only
through a defined interface.
You may note that up to this point we haven't done very much of
this in any of the examples; in fact, just about every variable
and method we've created has been fairly promiscuous and had no
access control whatsoever. The reason I approached the problem
in this way is that it makes for simpler examples. As you become
a more sophisticated programmer and create Java programs with
lots of interrelated classes, you'll find that adding features
such as encapsulation and protecting access to the internal
workings of your classes makes for better-designed programs
overall.
The Four Ps of Protection
The Java language provides four levels of protection for methods
and instance variables: public, private, protected, and package
(actually, the latter isn't an explicit form of Java protection,
but I've included it here because it's nicely alliterative).
Before applying protection levels to your own code, you should
know what each form means and understand the fundamental
relationships that a method or variable within a class can have
to the other classes in the system.
Note
You can also protect entire classes using these modifiers.
But class protection applies better once you know what
packages are, so we'll postpone talking about that until
tomorrow.
Package Protection
The first form of protection we'll talk about is the one you've
been unconsciously using all this time: what's called package
protection. In C, there's the notion of hiding a name so that
only the functions within a given source file can see it. Java
doesn't have this kind of control; names will be happily found
in other source files as long as Java knows where to find them.
Instead of file-level protection, Java has the concept of
packages, which, as you learned on Day 2, "Object-Oriented
Programming and Java," and will learn a whole lot more about
tomorrow, are a group of classes related by purpose or function.
Methods and variables with package protection are visible to all
other classes in the same package, but not outside that package.
This is the kind of protection you've been using up to this
point, and it's not much protection at all. Much of the time
you'll want to be more explicit when you define the protection
for that class's methods and variables.
Package protection, the default level of protection, means that
your methods and variables are accessible to all the other
classes in the same package.
Package protection isn't an explicit modifier you can add to
your method or variable definitions; instead, it's the default
protection you get when you don't add any protection modifiers
to those definitions.
Note
You may not think you've been using packages at all up to
this point, but actually, you have. In Java, if you don't
explicitly put a class into a package, it'll be included in
a default package that also includes all the other classes
that aren't in a specific package. While not defining a
class to be in a package works for simple examples, it's
better if you just create packages instead.
Private
From the default protection you get with package protection, you
can either become more restrictive or more loose in how you
control the visibility and access to your methods and variables.
The most restrictive form of protection is private, which limits
the visibility of methods and instance variables to the class in
which they're defined. A private instance variable, for example,
can be used by methods inside the same class, but cannot be seen
or used by any other class or object. Private methods,
analogously, can be called by other methods inside that same
class, but not by any other classes. In addition, neither
private variables nor private methods are inherited by
subclasses.
Private protection means that your methods and variables are
accessible only to other methods in the same class.
To create a private method or instance variable, add the private
modifier to its definition:
class Writer {
private boolean writersBlock = true;
private String mood;
private int income = 0;
private void getIdea(Inspiration in) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -