java基础——随笔03

发布时间 2023-09-23 11:19:56作者: 小白龙白龙马

java中this的用法:

 

一. this关键字

1.this的类型:哪个对象调用就是哪个对象的引用类型

 

 

 

二.用法总结

1.this.data; //访问属性
2.this.func(); //访问方法
3.this(); //调用本类中其他构造方法

 

 

三.解释用法

1.this.data
这种是在成员方法中使用

让我们来看看不加this会出现什么样的状况:

 

class MyDate{
    public int year;
    public int month;
    public int day;
 
    public void setDate(int year, int month,int day){
        year = year;//这里没有加this
        month = month;//这里没有加this
        day = day;//这里没有加this
    }
    public void PrintDate(){
        System.out.println(year+"年 "+month+"月 "+day+"日 ");
    }
}
public class TestDemo {
    public static void main(String[] args) {
        MyDate myDate = new MyDate();
        myDate.setDate(2000,9,25);
        myDate.PrintDate();
        MyDate myDate1 = new MyDate();
        myDate1.setDate(2002,7,14);
        myDate1.PrintDate();
    }
}

 

 

 

 

 

 

 

 

 而当我们加上this时:

class MyDate{
    public int year;
    public int month;
    public int day;
 
    public void setDate(int year, int month,int day){
       this.year = year;
       this.month = month;
       this.day = day;
    }
    public void PrintDate(){
        System.out.println(this.year+"年 "+this.month+"月 "+this.day+"日 ");
    }
}
public class TestDemo {
    public static void main(String[] args) {
        MyDate myDate = new MyDate();
        myDate.setDate(2000,9,25);
        myDate.PrintDate();
        MyDate myDate1 = new MyDate();
        myDate1.setDate(2002,7,14);
        myDate1.PrintDate();
    }
}

 

 

 

 

 

 2.this.func()
这种是指在普通成员方法中使用this调用另一个成员方法

class Student{
    public String name;
    public void doClass(){
        System.out.println(name+"上课");
        this.doHomeWork();
    }
    public void doHomeWork(){
        System.out.println(name+"正在写作业");
    }
}
public class TestDemo2 {
    public static void main(String[] args) {
        Student student = new Student();
        student.name = "小明";
        student.doClass();
    }
}

 

 

 

 

 

 

 

(3)this()
这种指在构造方法中使用this调用本类其他的构造方法

这种this的使用注意以下几点
1.this只能在构造方法中调用其他构造方法
2.this要放在第一行
3.一个构造方法中只能调用一个构造方法

 

 

 

 

 

 

 

 

 

 ===============================================================================

 

 

 

 

 

 

 

 java中super的用法:

 

 

 

 

super只在子类中出现,super有三种用法:

 

【1】 super.xxx;
xxx可以是类的属性。
例如super.name;即从子类中获取父类name属性的值

 

【2】 super.xxx();
xxx()可以是类中的方法名。
super.xxx();的意义是直接访问父类中的xxx()方法并调用

 

【3】 super();
此方法意义是直接调用父类的构造函数。
super(无参/有参)即调用父类中的某个构造方法,括号里的内容根据你所调用的某个构造函数的变化而改变

 

 

 

 

 

 

 ==================================================================================

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

============================================================================

 

 

 

 

 

 

java中final的用法

 

 

 

 

 

 

1