• Java中this与super的区别


    this与super关键字在java中构造函数中的应用: 
    **

    super()函数

    ** 
    super()函数在子类构造函数中调用父类的构造函数时使用,而且必须要在构造函数的第一行,例如:

    class Animal {
        public Animal() {
            System.out.println("An Animal");
        }
    }
    class Dog extends Animal {
        public Dog() {
            super();
            System.out.println("A Dog");
            //super();错误的,因为super()方法必须在构造函数的第一行
            //如果子类构造函数中没有写super()函数,编译器会自动帮我们添加一个无参数的super()
        }
    }
    class Test{
        public static void main(String [] args){
            Dog dog = new Dog();
        }
    }

    执行这段代码的结果为:

    An Animal 
    A Dog

    定义子类的一个对象时,会先调用子类的构造函数,然后在调用父类的构造函数,如果父类函数足够多的话,会一直调用到最终的父类构造函数,函数调用时会使用栈空间,所以按照入栈的顺序,最先进入的是子类的构造函数,然后才是邻近的父类构造函数,最后再栈顶的是最终的父类构造函数,构造函数执行是则按照从栈顶到栈底的顺序依次执行,所以本例中的执行结果是先执行Animal的构造函数,然后再执行子类的构造函数。

    class Animal {
        private String name;
        public String getName(){
            name = name;
        }
        public Animal(String name) {
            this.name = name;
        }
    }
    class Dog extends Animal {
        public Dog() {
            super(name);
        }
    }
    class Test{
        public static void main(String [] args){
            Dog dog = new Dog("jack");
            System.out.println(dog.getName());
        }
    }

    运行结果:

    jack

    当父类构造函数有参数时,如果要获取父类的private的成员变量并给其赋值作为子类的结果,此时在定义子类的构造函数时就需要调用父类的构造函数,并传值,如上例所示。

    this()函数

    this()函数主要应用于同一类中从某个构造函数调用另一个重载版的构造函数。this()只能用在构造函数中,并且也只能在第一行。所以在同一个构造函数中this()和super()不能同时出现。 
    例如下面的这个例子:

    class Mini extends Car {
        Color color;
        //无参数函数以默认的颜色调用真正的构造函数
        public Mini() {
            this(color.Red);
        }
        //真正的构造函数
        public Mini(Color c){
            super("mini");
            color = c;
        }
        //不能同时调用super()和this(),因为他们只能选择一个
        public Mini(int size) {
            super(size);
            this(color.Red);
    }

    `所以综上所述,super()与this()的区别主要有以下: 
    不同点: 
    1、super()主要是对父类构造函数的调用,this()是对重载构造函数的调用 
    2、super()主要是在继承了父类的子类的构造函数中使用,是在不同类中的使用;this()主要是在同一类的不同构造函数中的使用 
    相同点: 
    1、super()和this()都必须在构造函数的第一行进行调用,否则就是错误的

  • 相关阅读:
    TeeChart的X轴,使用伪装的时间
    线程池
    修练8年C++面向对象程序设计之体会
    使用RESTClient插件数据模拟(GET,POST)提交
    :施密特建议尾随年轻的专业人士了解技术公司
    社会保障系列1《介绍》
    Centos根据系统VPS安装SendMail组件使WordPress支持E-mail
    Codeforces Round #107 (Div. 2)---A. Soft Drinking
    [Unity3D]Unity3D游戏开发3D选择场景中的对象,并显示轮廓效果强化版
    怎么样ubuntu 64 11.04 在执行32位程序
  • 原文地址:https://www.cnblogs.com/zmy-520131499/p/11166600.html
Copyright © 2020-2023  润新知