zoukankan      html  css  js  c++  java
  • 构造函数中的super和this的使用

    super用于调用父类构造函数的部分,其必须出现在构造函数的第一行。super在调用时第一件事就是去执行父类构造函数的部分,所执行的父类构造函数与super()括号中的参数相对应。

    this用于在一个构造函数中调用同一个类另一个构造函数,其也必须是第一行语句。

    super和this不能同时出现在一个构造函数中,其两个在使用时必须出现在构造函数的第一行语句,其区别为super调用父类构造函数,this调用自身类的构造函数。

    为便于理解,可以将this理解为自己,也就是这个类本身,因此调用this是调用自己类的构造函数。

    public abstract class Animal {
        private String name;
        public String getName() {
            return name;
        }
        public Animal() {
            
        }
        public Animal(String theName) {
            name=theName;
        }
        public Animal(String x,String getname) {
            
        }
    
    }
    public class Hippo extends Animal{
        String name;
        public Hippo() {    //编写此构造函数父类需也有无参构造函数
            String test;
        }
        public Hippo(String name) {
            super(name);    //使用super方法将name传给父类Animal
            System.out.println("big");
        }
        
        public Hippo(String x,String name) {
            this(name);        //this为调用只有一个string参数的构造函数,即调用上面的构造函数输出big
            //super(name);    //super和this只能调用一个
            System.out.println(x);
            
        }
    
    }

    输出结果为

    big
    Buffy

  • 相关阅读:
    Kaggle 神器 xgboost
    改善代码可测性的若干技巧
    IDEA 代码生成插件 CodeMaker
    Elasticsearch 使用中文分词
    Java性能调优的11个实用技巧
    Lucene 快速入门
    Java中一个字符用unicode编码为什么不是两字节
    lucene 的评分机制
    面向对象设计的 10 条戒律
    2019.10.23-最长全1串(双指针)
  • 原文地址:https://www.cnblogs.com/do-hardworking/p/10464366.html
Copyright © 2011-2022 走看看