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

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类 
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值