您的位置:首页 > 其它

一个例子对于类继承和关键字“this”的理解

2007-03-09 16:48 435 查看
package com.yhy;

class Person5
{
static int count=0;
protected String name;
protected int age;
public Person5(String n1,int a1)
{
name=n1;
age=a1;
this.count++;
}
public String toString()
{
return this.name+","+this.age;
}
public void display()
{
System.out.print("本类名="+this.getClass().getName()+";");
System.out.println("父类名="+this.getClass().getSuperclass().getName());
System.out.print("Person5.count="+this.count+" ");
System.out.print("Student5.count="+Student5.count+" ");

Object obj=this;
if(obj instanceof Student5)
System.out.println(obj.toString()+"是Student5类对象");
else if(obj instanceof Person5)
System.out.println(obj.toString()+"是Persont5类对象");
}
}

class Student5 extends Person5
{
static int count=0;
protected String dept;
protected Student5(String n1,int a1,String d1)
{
super(n1,a1);//继承父类构造函数
dept=d1;
this.count++;
}
public String toString()
{
return super.toString()+","+dept;
}
public void display()
{
super.display();
System.out.print("super.count="+super.count);
System.out.println(";this.count="+this.count);
}
}

public class app8_9 {

public static void main(String[] args) {
Person5 per=new Person5("王老五",23);
per.display();

Student5 stu=new Student5("张小三",22,"计算机系");
stu.display();
}
}

打印输出结果如下所示(打印内容共3行):

本类名=Student5;父类名=Person5

Person5.count=2 Student5.count=1 张小三,22,计算机系是Student5类对象

super.count=2;this.count=1

我想要问的问题是:
(1)打印输出结果的第2行中的第一个count的值为什么是2而不是1?
(2)父类中的display()方法和父类的构造方法中的this关键字到底分别指的是什么?

******************************************************************
恢复:

打印输出结果的第2行中的第一个count的值为什么是2而不是1?
因为在运行Person5 per=new Person5("王老五",23);时,Person5.count已经加1了

父类中的display()方法和父类的构造方法中的this关键字都指的是Person5类
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: