《JAVA编程思想》学习备忘(第209页:Access Control)-2

续《JAVA编程思想》学习备忘(第209页:Access Control)-1
Using imports to change behavior
A feature that is missing from Java is C's conditional compilation,which allows you to change a switch and get different behavior without changing any other code.The reason such a feature was left out of Java is probably because it is most often used in C to solve cross-platform issues:Different portions of the code are compiled depending on the target platform.Since Java is intended to be automatically cross-platform,such a feature should not be necessary.
However,there are other valuable uses for conditional compilation.A very common use is for debugging code.The debugging features are enabled during development and disabled in the shipping product.You can accomplish this by changing the package that's imported in order to change the code used in your program from the debug version to the production version.This technique can be for any kink of conditional code.
 
Package caveat
It's worth remembering that anytime you create a package,you implicitly specify a directory structure when you give the package a name.The package must live in the directory indicated by its name,which must be a directory that is searchable starting from the CLASSPATH.Experimenting with the package keyword can be bit frustration at first,because unless you adhere to the package-name to directory-path rule,you'll get a lot of mysterious runtime messages about  not being able to find a particular class,even if that class is sitting there in the same directory.If you get a message like this,try commenting out the package statement,and if it runs,you'll konw where the problem lies.
Note the compiled code is often placed in a different directory than source code,but the path to the compiled code must still be found by the JVM using the CLASSPATH. 
 
Java access specifiers
......Each access specifier only controls the access for that particular definition.
If you don't provide an access specifier,it means"package access."So one way or another,everything has some kind of access control.In the following sections,you'll learn about the various types of access.
Package access
......It means that all the other classes in the current package have access to that member,but to all the classes outside of this package,the member appears to be private.
......The only way to grant access to a member is to:
1.Make the member public.Then everybody,everywhere,can access it.
2.Give the member package access by leaving off any access specifier,and put the other classes in the same package.Then the other clases in that package can access the member.
3.As you'll see in the Reusing Classes chapter,when inheritance is introduced,an inherited class can access a protected member as well as a public member(but not private members).It can access package-access members only if the tow classes are in the same package.But don't worry about inheritance and protected right now.
4.Provide"accessor/mutator"methods(also known as"get/set" methods)that read and change the value.This is the most civilized approach in terms of OOP,and it is fundamental to JavaBeans,as you'll see in the Graphicla User Interfaces chapter.
 
public:interface access
举例:
//:access/desert/Cookie.java
//Creates a library.

package access.dessert;

 

public class Cookie {
    public Cookie(){
     System.out.println("Cookie constructor");
    }
    void bite(){System.out.println("bite");}
}

 

//:access/Dinner.java

//Uses the library.

import access.dessert.*;
public class Dinner {
 public static void main(String[] args) {
     Cookie x = new Cookie();
     //! x.bite();//Can't access
 }
}

输出结果:

Cookie constructor

(注意看以上代码内注释掉的部分)

 

The default package

You might surprised to discover that the following code compiles,even though it would appear that it breaks the rules:

 

//:access/Cake.java

//Access a class in a separate compilation unit.

class Cake{

    public static void main(String[] args){

        Pie x = new Pie();

        x.f();

    }

}

输出结果:

Pie.f()

In a second file in the same directory:

//:access/Pie.java

//The other class.

class Pie{

    void f(){System.out.println("Pie.f()");}

}

 

private:you can't touch that!

The private keyword means that no one can access that member except the class that contains that member,inside methods of that class.

private allows you to freely change that member without concern that it will affect another class in the same package.

举例:

//:access/IceCream.java

//Demonstrates "private" keyword.

class Sundae{

    private Sundae(){}

    static Sundae makeASundae(){

        return new Sudnae();

    }

}

 

public class IceCream{

    public static void main(String[] args){

        //!Sundae x = new Sundae();

        Sundae x = Sundae.makeASundae();

    }

}

This shows an example in which private comes in dandy:You might want to control how an object is created and prevent someone from directly accessing a particular constructor(or all of them).In the preceding example,you cannot create a Sundae object via its constructor;instead,you must call the makeASundae() method to do it for you.

Unless you must expose the underlying implementation(which is less likely than you might think),you should make all fields private.

protected:inheritance access

The protected keyword deals with a concept called inheritance.which takes an existing class-which we refer to as the base class-and adds new members to that class without touching the existing class.You can also change the behavior of existing members of the class.To inherit from a class,you say that your new class extends an existing class,like this:

class Foo extends Bar{

The rest of the class definition looks the same.

If you create a new package and inherit from a class in another package,the only members you have access to are the public members of the original package.(Of course,if you perform the inheritance in the same package,you can manipulate all the members that have package access.)Sometimes the creator of the base class would like to take a particular member and grant access to derived classes but not the world in general.That's what protected does.protected also gives package access-that is,other classes in the same package may access protected elements.

If you refer back to the file Cookie.java,the following class cannot call the package-access member bite();

//:access/ChocolateChip.java

//Can't use package-access member from another package.

import access.dessert.*;

public class ChocolateChip extends Cookie{

    public ChocolateChip(){

        System.out.println("ChocolateChip constructor");

    }

    public void chomp(){

    //!bite();//Can't access bite

    }

    public static void main(String[] args){

        ChololateChip x = new ChocolateChip();

        x.chomp();

    }

}

输出结果:

Cookie constructor

ChocolateChip constructor

One of the interesting things about inheritance is that if a method bite() exists in class Cookie,then it also exists in any class inherited from Cookie.But since bite() has package access and is in a foreign package,it's unavailable to us in this one .Of course,you could make it public,but then everyone would have access,and maybe that's not what you want.If you change the class Cookie as follows:

//:access/cookie2/Cookie.java

package access.cookie2;

public class Cookie{

    public Cookie(){

        System.out.println("Cookie constructor");

    }

    protected void bite(){

        System.out.println("bite");

    }

}

now bite() becomes accessible to anyone inheriting from Cookie:

//:access/ChocolateChip2.java

import access.cookie2.*;

public class ChocolateChip2 extends Cookie{

    public ChocolateChip2(){

        System.out.println("ChocolateChip2 constructor");

    }

    public void chomp(){bite();}//Protected method

    public static void main(String[] args){

        ChocolateChip2 x = new ChocolateChip2();

        x.chomp();

    }

}

输出结果:

Cookie constructor

ChocolateChip2 constructor

bite

 

(待续)

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值