this是指当前调用这个方法的对象, public int olderthen(Person4 b) //比较两个人的年龄 { Person4 a = this; //指代对象本身 return a.age - b.age; } 已知我们创建了2个对象p1和p2,当我们调用p1.olderthen(p2)时,其中public int olderthen(Person4 b) 中的b指的是p2。对于Person4 a = this;这句话中的this指的就是当前调用这个方法的对象p1,所以a得到的是p1的引用值,所以return a.age - b.age;返回的是p1和p2的年龄差。
public class Person4
{
static int count=0;
protected String name;
protected int age;
public Person4(String n1,int a1) //构造方法
{
this.name = n1;
this.age = a1;
this.count++;
}
public int olderthen(Person4 b) //比较两个人的年龄
{
Person4 a = this; //指代对象本身
return a.age - b.age;
}
public void print()
{
System.out.print(this.getClass().getName()+" ");
System.out.print("count="+this.count+" ");
System.out.println(" "+this.name+", "+this.age);
}
}
class Student4 extends Person4
{
protected String dept;
Student4(String n1,int a1,String d1) //不能继承超类的构造方法
{
super(n1,a1); //调用超类的构造方法
dept = d1;
}
public static void main(String args[])
{
Person4 p1 = new Person4("李大广",21);
p1.print();
Student4 s1 = new Student4("陈小瑞",19,"计算机系") ;
s1.print();
System.out.println("年龄差= "+p1.olderthen(s1));
}
}
public int olderthen(Person4 b) //比较两个人的年龄
{
Person4 a = this; //指代对象本身
return a.age - b.age;
}
已知我们创建了2个对象p1和p2,当我们调用p1.olderthen(p2)时,其中public int olderthen(Person4 b) 中的b指的是p2。对于Person4 a = this;这句话中的this指的就是当前调用这个方法的对象p1,所以a得到的是p1的引用值,所以return a.age - b.age;返回的是p1和p2的年龄差。
{
return (this.a).age - b.age;
}
public int olderthen(Person4 b)
{
return this.age - b.age;
}这样就完了, 他写了句废话