this使用位置
this的三种用法
this.成员变量名
class Fu {public String name ="父类的名字";public int age =22;
}class Zi extends Fu {public int age = 18;public void test() {int age = 20;//当方法的局部变量与当前对象的成员变量重名时,就可以在成员变量前面加this.System.out.println(this.age); //18/*this.成员变量会先从本类声明的成员变量列表中查找,如果未找到,会去从父类继承的在子类中仍然可见的成员变量列表中查找*/System.out.println(this.name); //父类的名字}
}
public class Demo01{public static void main(String[] args) {Zi zi = new Zi();zi.test();}
}
this.成员方法
class Fu {public void demo() {System.out.println("我是父类可见成员方法");}
}class Zi extends Fu {public void test() {//调用当前对象的成员方法时,都可以加"this.",也可以省略,实际开发中都省略this.show(); //张三this.demo(); //我是父类可见成员方法}public void show() {System.out.println("张三");}
}public class Demo01 {public static void main(String[] args) {Zi zi = new Zi();zi.test();}
}
this()或this(实参列表)
class Zi {private String name;private int age;private char sex;public Zi() {}public Zi(String name, int age) {this.name = name;this.age = age;}public Zi(String name, int age, char sex) {//只能调用本类的其他构造器且必须在构造器的首行this(name, age); this.sex = sex;}}
含义:super代表当前对象中从父类的引用的
super使用的前提
super的三种用法
super.成员变量
在子类中访问父类的成员变量,特别是当子类的成员变量与父类的成员变量重名时。
class Father{int a = 10;
}
class Son extends Father{int a = 20;public void test(int a){//在子类中访问父类的成员变量,特别是当子类的成员变量与父类的成员变量重名时。System.out.println(super.a);//10//访问本类的成员变量System.out.println(this.a);//20//访问本方法的局部变量System.out.println(a);//30}
}
public class Test{public static void main(String[] args){Son s = new Son();s.test(30);}
}
super.成员方法
在子类中调用父类的成员方法,特别是当子类重写了父类的成员方法时
class Father{public void method(){System.out.println("父类方法");}
}
class Son extends Father{public void test(){//调用子类方法method();//子类方法super.method();//父类方法}public void method(){System.out.println("子类方法");}
}public class Test{public static void main(String[] args){Son s = new Son();s.test();}
}
super()或super(实参列表)
在子类的构造器首行,用于表示调用父类的哪个实例初始化方法。super() 和 this() 都必须是在构造方法的第一行,所以不能同时出现。
class Father {private String name;public Father(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}
}class Son extends Father {public Son( String name) {super(name);//调用父类中的构造方法}public void show(){System.out.println("名字:" + super.getName());}
}public class Test {public static void main(String[] args) {Son s = new Son("张三");s.show(); //名字:张三}
}
没有super和this
存在this
通过this找变量时,先从当前执行代码的本类中的成员变量开始找,没有的会往上找父类的(非private,跨包还不能是缺省的)。
存在super
注意:super和this都不能出现在静态方法和静态代码块中,因为super和this都是存在与对象中的
没有super和this
先从当前对象(调用方法的对象)的本类找,如果没有,再从父类继承的可见的方法列表中查找,再没有,继续往上追溯
存在this
先从当前对象(调用方法的对象)的本类找,如果没有,再从父类继承的可见的方法列表中查找,再没有,继续往上追溯
存在super
直接从当前对象(调用方法的对象)的父类继承的可见的方法列表中查找,再没有,继续往上追溯
找构造器