Java重载、访问控制

Employee.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public abstract class Employee {
private String name;

protected String color;

protected String firm;

public String info;

protected String info2;

public Employee(String n) {
name = n;
firm = "1";
info = "3";
info2 = "233";
}

public Employee() {
name = "Unknown";
firm = "2";
info = "4";
info2 = "2334";
}

public abstract void describeShape();
}

SalariedEmployee.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class SalariedEmployee extends Employee {
private double weeklySalary;

private String color;

public int info2;

private class Inner {
private double hour;

public double getWeeklySalary() {
return weeklySalary; // 内部类访问外部的变量,
// 也就是:Nested class has access to the members (including private
// members) of the enclosing class
}
}

private Inner inner = new Inner();

public double do_something_inner_class() {
// hour = 3; // 这样不行,就是说外部类不能直接访问内部类的东西,得要先new一个对象再访问
// Enclosing class does not have access
//to the members of the nested class
// 或者说外部类没有直接的内部类的东西,但是内部类有外部类的东西
inner.hour = 3; // 但是直接用一个内部类的对象是可以访问内部类的private的变量的
return inner.getWeeklySalary();
}

public void do_something_supre_class() {
firm = "3"; // 父类的protected可以访问
info = "$"; // 父类的public的可以访问
// name = "2"; // 父类的private的不能访问
}

@Override
public void describeShape() {
System.out.println("hhh");
}

public static void main(String[] args) {
SalariedEmployee e = new SalariedEmployee();
e.describeShape();
System.out.println(e.info2);
System.out.println(((Employee)e).info2);
}
}