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

  • 相关阅读:
    安装jdk1.8导致eclipse显示问题
    Linux创建定时任务
    Burp suite抓取HTTPS请求
    Webbench性能测试
    Fiddler抓取手机Https请求
    Linux下使用Jmeter做性能测试
    Charles抓取手机https请求
    Jmeter发送Java请求
    Linux搭建JDK、Tomcat安装及配置
    Loadrunner监控Apache
  • 原文地址:https://www.cnblogs.com/do-hardworking/p/10464366.html
Copyright © 2011-2022 走看看