java中的小疑惑
/*
疑问1:类的封装过程中关于私有变量的this引用问题?
在构造函数中:this代表当前正在创建的对象;在普通函数中:this代表当前正在调用该方法的对象。this可看成是对象。
在构造函数中this.name = name 中成员变量name是private,怎么可以用对象名去访问私有成员?
在普通函数中String strinf =this.name + ":" + this.age; 其中的name和age都是私有变量,怎么可以
用调用GetInfor()方法的对象名去访问私有变量?
疑问2:类继承过程中,普通函数的调用问题?
类的继承过程中,子类也继承了父类的非静态普通成员函数,在父类Human和子类Student中都有GetInfor()方法,
创建对象st1后,调用st1.GetInfor(),是调用Human中的GetInfor(),还是调用Student中的GetInfor()?
*/
class Human
{
private String name;
private int age;
public Human()
{
}
public Human(String name, int age)
{
this.name = name;
this.age = age;
}
public String GetInfor()
{
String strinf =this.name + ":" + this.age;
return strinf;
}
}
class Student extends Human
{
private String school;
public Student()
{
}
public Student(String name, int age, String school)
{
//this.name = name;//error 私有成员不能继承
//this.age = age;//error 私有成员不能继承
super(name, age);
this.school = school;
}
public String GetInfor()
{
//String strinf = name + ":"+ age + ":" + school;//error 子类不能继承父类的私有成员
String strinf =super.GetInfor() + ":" + this.school;//用super调用父类的普通方法
return strinf;
}
}
class TestSuper_2
{
public static void main(String[] args)
{
Student st1 = new Student("张三", 12, "北大");
System.out.printf("%s\n", st1.GetInfor());
}
}