zoukankan      html  css  js  c++  java
  • 理解Java中this关键字作用 |||| Java中的静态绑定与动态绑定 |||| 子类继承父类的变量域

    1.参考代码

    public class class_train
    {
        public static void main(String[] args) {
            // System.out.println(name)
            Employee[] staffs = new Employee[2];
            Manager boss = new Manager("ljy", 2000,3000);
            staffs[0] = boss;
            staffs[1] = new Employee("yfc", 1200);
            System.out.println(staffs[1].nextID);
            System.out.println(staffs[0].getClass());
            System.out.println(staffs[1].getClass()); 
            System.out.println(staffs[0].getsalary());
            System.out.println(staffs[1].getsalary());
        }
    }
    
    class Employee
    {
        public int nextID = 1;
        private String name;
        private int salary;
        public Employee(String name, int salary)
        {
            this("Employee ID#", name, salary);
            nextID++;
        }
        public Employee(String ID, String name, int salary)
        {
            System.out.println("second Constructor");
            this.nextID++;
            this.name = name;
            this.salary = salary;
        }
        public int getsalary()
        {
            return this.salary;
        }
    }
    
    class Manager extends Employee
    {
        private int honor;
        public Manager(String name, int salary, int honor){
            super(name, salary);
            this.honor = honor;
        }
        public int getsalary()
        {
            return super.getsalary() + this.honor;
        }
    }
    
    //这段代码输出
    second Constructor
    second Constructor
    3
    class Manager
    class Employee
    5000
    1200
    

    2.this关键字的作用

    this关键字有两个作用

    1. 调用自身类的公开的方法和属性。
    2. 调用自身的其他构造方法
      参考代码中的构造器就使用this调用了另外一个构造器(注意构造构造器的时候签名要严格一致)
      以及调用对象中其它方法。

    3.Java中的静态绑定与动态绑定

    静态绑定和动态绑定表示编译器(JVM)对不同方法的调用方式。

    1. 静态绑定
      如果是使用private ,final ,static 创建的方法,编译器可以直接知道应该调用什么方法
    2. 动态绑定
      如果不是之前说的三种方式创建的方法,那么虚拟机一定会调用我们所引用的对象中最合适哪一个类方法。包括会在父类中搜索。但是事实上如果真的是在其中进行搜索,所需要的时间开销会很大,所以JVM会创建一个包含所有方法的方法表,所以需要找到调用方法的时候只要在方法表中找到最合适的方法就可以了。

    4.子类继承父类的变量域

    在上述代码中我们创建了一个Manager类继承了Employee类,同时我们在创建Manager的构造方法的时候调用的Employee类的构造方法。可以从输出看出确实是创建子类的时候确实是调用了父类的构造方法。我们使用super关键字将参数传给父类构造器,注意super需要写在子类构造器的第一行。

  • 相关阅读:
    JAVA SkipList 跳表 的原理和使用例子
    TreeMap、HashMap、ConcurrentSkipListMap之性能比较
    CompletionService 和ExecutorService的区别和用法
    1. java.util.concurrent
    JAVA Concurrent包 中的并发集合类
    并发队列ConcurrentLinkedQueue和阻塞队列LinkedBlockingQueue用法
    Objective-C中 ==、isEqual、isEqualToString判断字符串相等
    设置UIButton的文字显示位置、字体的大小、字体的颜色
    9个完整android开源app项目
    android 开源项目集合
  • 原文地址:https://www.cnblogs.com/yfc0818/p/11072604.html
Copyright © 2011-2022 走看看