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));//第二个注释
}
}
/****************************************************************
请问p1.olerthen(s1)传过去的是什么,是否是一个类实例
public int olderthen(Person4 b)接收的是什么?接收之后的b.age是谁的类呢?
这种用法第一次看到请高手指教.
*******************************************************************/
{
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));//第二个注释
}
}
/****************************************************************
请问p1.olerthen(s1)传过去的是什么,是否是一个类实例
public int olderthen(Person4 b)接收的是什么?接收之后的b.age是谁的类呢?
这种用法第一次看到请高手指教.
*******************************************************************/
接收的是一个Student4对象,也是Person4对象,因为了Student4继承了Person4
b.age是Person4是的
为:
public int olderthen(Student4 b)//第一个注释;
那么接收的是什么呢?
那么:a.age也是Person4的那么:return a.age-b.age;应该等于0
那么结果怎么输出:2呢.
您的说法是不是有误啊?
System.out.println(this.dept);
就不行了, 因为父类中没有这个属性,只有子类中才有,必须先转回子类的类型
修改为:
public int olderthen(Student4 b)
那么这时传递的就是Student4的实例的引用,但这时就不能传递Person4的实例引用了,这样做不符合java的思想,因为你限制了传递的参数的类型,如果以后要传递另外的类型,你还得重写方法,这不麻烦吗?
那么结果怎么输出:2呢.
您的说法是不是有误啊?
-------------------------------------------------------------没有错误啊~!
b.age是这个类的实例的属性,注意,是实例的属性~!传递进来的Student4类的实例向上转型后,其属性并未丢失,所以b.age = 19
public class aa
{
int num=99;
void jj(aa f)
{
System.out.println(f.num);
System.out.println(f.getClass().getName());
System.out.println(f.sex);//注释
}}
class bb extends aa
{ String sex="男";
bb()
{
num=88;
}
public static void main(String args[])
{
bb b=new bb();
aa a=new aa();
a.jj(b);
}
}如果不把带有//注释的那一行注释掉的话,会提示找不到变量set
但是我传递的是bb类的实例啊?而且bb类实例中有sex这个变量啊?
这时程序到底是怎么执行的啊?我真的晕了