------- android培训、java培训、期待与您交流! ----------
this 的属性调用
例1:
class Persov
{
private String name;
private int age;
Persov(String name)
{
this.name = name; //当 h (h1)这个对象在调用 Persov 这个构造函数时,this就代表 h (h1)这个对象。
}
Persov(String name,int age)
{
this.name = name;
this.age = age;
}
public void talk()
{
System.out.println(name+"\t"+age);
}
}
public class JavaTest4 {
public static void main(String[] args) {
Persov h = new Persov("wang",20);
h.talk();
Persov h1 = new Persov("zhang");
h1.talk();
}
}
运行结果:
wang 20
zhang 0
点评: this 是用于区分成员变量和局部变量同名的情况。哪个对象在调用this所在的函数,this就代表哪个对象。
例2: 定义一个用于比较年龄是否相同的功能。也就是是否是同龄人。
class Persoc
{
private int age;
Persoc(int age)
{
this.age = age;
}
public boolean compare(Persoc p)
{
return this.age == p.age; //定义类中的函数(compare)时,该函数(compare)内部要用到调用该函数(compare)的对象(p1)时,用this来表示这个对象(p1).
}
}
public class Test {
public static void main(String[] args) {
Persoc p1 = new Persoc(23);
Persoc p2 = new Persoc(25);
System.out.println(p1.compare(p2)); //p1调用了函数(compare)。
}
}
运行结果:
false
点评: 本类功能内部使用了本类对象,用this表示。
super 的属性调用
例1: super 调用父类中的属性和方法。
class Person
{
String name;
int age;
public Person()
{
}
public String talk()
{
return "woshi:"+this.name+",jinnian:"+this.age+"sui";
}
}
class Student extends Person
{
String school;
public Student(String name,int age,String school)
{
super.name = name;
super.age = age; // super 调用父类中的属性
System.out.print(super.talk()); // super 调用父类中的方法
// super 关键字不仅可以用于调用父类中的构造方法,也可以用于调用父类中的属性或方法。
this.school = school;
}
}
public class Test01
{
public static void main(String[] args)
{
Student s = new Student("zhangsan",25,"beijin");
System.out.println(",xuexiao:"+s.school);
}
}