0
点赞
收藏
分享

微信扫一扫

Java关键字(二):this 和 super

三次方 2022-04-14 阅读 27

Java关键字(二):this 和 super



前言

本博主将用CSDN记录软件开发求学之路上亲身所得与所学的心得与知识,有兴趣的小伙伴可以关注博主!
也许一个人独行,可以走的很快,但是一群人结伴而行,才能走的更远!让我们在成长的道路上互相学习,欢迎关注!

一、“ this ”关键字的使用

1. 概述

  • this是什么?

2. 作用

3. 使用

  • 什么时候使用this关键字呢?

3.1 修饰属性和方法

代码演示:

class Person{ // 定义Person类
    private String name ;
    private int age ;
    public Person(String name,int age){
      this.name = name ; 
      this.age = age ; }
    public void getInfo(){
      System.out.println("姓名:" + name) ;
      this.speak();
    }
    public void speak(){
      System.out.println(“年龄:” + this.age);
    } 
}

3.2 调用构造器

代码演示:

class Person{ // 定义Person类
   private String name ;
   private int age ;
   public Person(){ // 无参构造器
     System.out.println("新对象实例化") ;
   }
   public Person(String name){
     this(); // 调用本类中的无参构造器
     this.name = name ;
   }
   public Person(String name,int age){
     this(name) ; // 调用有一个参数的构造器
     this.age = age;
   }
   public String getInfo(){
     return "姓名:" + name + ",年龄:" + age ;
   } 
}

3.3 返回当前对象

代码演示:

public class Leaf {
    int i = 0;
    Leaf increment(){
        i++;
        return this;
    }
    void print(){
        System.out.println("i = "+i);
    }
    public static void main(String args[]){
        Leaf x = new Leaf();
        x.increment().increment().increment().print();//i = 3
    }
}

二、“ super ”关键字的使用

1. 概述

2.使用

3.使用

3.1 调用属性和方法

3.2 调用构造器

代码演示:

public class Person {
    private String name;
    private int age;
    private Date birthDate;
    public Person(String name, int age, Date d) {
       this.name = name;
       this.age = age;
       this.birthDate = d; }
    public Person(String name, int age) {
       this(name, age, null);
    }
    public Person(String name, Date d) {
       this(name, 30, d);
    }
    public Person(String name) {
       this(name, 30);
    } 
}


public class Student extends Person {
    private String school;
    public Student(String name, int age, String s) {
      super(name, age);
      school = s; 
    }
    public Student(String name, String s) {
      super(name);
      school = s; 
    }
// 编译出错: no super(),系统将调用父类无参数的构造器。
    public Student(String s) { 
      school = s; 
    } 
}

三、this和super的区别

No.区别点thissuper
1访问属性访问本类中的属性,如果本类没有此属性则从父类中继续查找直接访问父类中的属性
2调用方法访问本类中的方法,如果本类没有此方法则从父类中继续查找直接访问父类中的方法
3调用构造器调用本类构造器,必须放在构造器的首行调用父类构造器,必须放在子类构造器的首行

四、子类对象实例化的全过程

举报

相关推荐

0 条评论