关于this的使用

来源:互联网 发布:python ctypes 安装 编辑:程序博客网 时间:2024/05/14 15:03

this的使用有四种:

(1)访问本类中的属性,如果本类中没有,则藏父类中继续查找

(2)访问本类中的方法,如果本类中没有,则从父类中继续查找
(3)调用本类构造器.必须放在构造器中的第一行

(4)表示当前对象

class Base{public Base(){System.out.println("Base构造器");}}class Sub extends Base{private int a;private String msg; public Sub(int a){this.a = a;                       // 访问本类中的实例变量a,System.out.println("一个参数的构造器");}public Sub(String msg){this.msg = msg;}public Sub(int a, String msg){this(a);                      // 调用一个参数 的构造器,必须位于第一行,//this(msg);                   不能调用两个System.out.println("两个参数的构造器");}public void test(){System.out.println("test()方法");}public void fun(){this.test();               // // 访问本类中的方法System.out.println("fun()方法");}}public class TestThis {public static void main(String[] args) {Sub s = new Sub(24, "liu");s.fun();}}
输出结果:

Base构造器一个参数的构造器两个参数的构造器test()方法fun()方法

注:在static方法中不能调使用his,因为对static修饰的方法属于类的,而不是属于类的实例,当在static方法中使用this关键字。会导致这个this无法指向合适的对象,

所以,static方法中不能使用this关键字,static方法不能直接访问非static方法。


0 0
原创粉丝点击