美文网首页
Java重载、访问控制 2020-04-06

Java重载、访问控制 2020-04-06

作者: 五道口的程序狐 | 来源:发表于2020-04-06 08:50 被阅读0次

Employee.java

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

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);
    }
}

相关文章

网友评论

      本文标题:Java重载、访问控制 2020-04-06

      本文链接:https://www.haomeiwen.com/subject/wyhvphtx.html