Skip to content

Commit

Permalink
add java modification
Browse files Browse the repository at this point in the history
  • Loading branch information
wxnacy committed Dec 28, 2018
1 parent 2e4339f commit 5ef3209
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
29 changes: 23 additions & 6 deletions java/modification/README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,33 @@
# Java 修饰关键词区别

Java 共有四种修饰:`public, private, protected, friendly`,(默认为:friendly)

可能调用他们修饰变量和函数的有的作用域有:当前类、当前包、子类、外部类

从网上找他们的对应的调用权限,很多是各种摘抄,并且存在各种错误,所以我认真对他们进行了实验,得到如下结论

```java
private int id
public String name
protected int age
int sex // 默认为:friendly
```

| 对比 | 当前类 | 当前包 | 子类 | 外部类 |
| --------- | ------ | ------ | ---- | ------ |
| public |||||
| private || × | × | × |
| protected |||| × |
| friendly |||| × |

如表格,简单总结如下

- `public`: 所有地方都可以调用。
- `private`: 只有当前类可以调用。
- `protected`: 只有外部类不可调用。
- `friendly`: 与 `protected` 完全相同。

下载本文件夹到电脑中,确保电脑中有 Java 运行环境,可以执行跟目下的 `./run.sh` 脚本。

```bash
$ ./run.sh
public private protected friendly
当前类 √ √ √ √
当前包 √ × √ √
子类 √ × √ √
外部类 √ × × ×
```
2 changes: 1 addition & 1 deletion java/modification/src/bean/Man.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ public class Man extends Person {


public String test() {

Man m = new Man();
// private String n2; 在子类中不可使用
m.n1 = "√";
Expand Down

0 comments on commit 5ef3209

Please sign in to comment.