父类:
package homework;
public class people
{
private String name;
private int age;
public String getName() {
System.out.print(name);
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
System.out.print(age);
return age;
}
public void setAge(int age) {
this.age = age;
}
public void say()
{
System.out.println("美丽动听的人类语言");
}
public people()
{
}
public people(String name,int age)
{
this.name=name;
this.age=age;
}
public static void main(String[] args)
{
}
}
子类:
package homework;
/*在子类中没有定义name和age属性,只是在父类里定义的,但也能应用在这里,这便是继承的意义
* 但分为两种
* 1)name和age为public型的,此时只要写子类构造器时参数写成四个(在本题的例子中,其他具体而定)直接应用即可
* 2)name和age为私有的,则不能直接调用了,此时只要在父类中写出属性(即name和age)的public的get和set 方法,
* 在子类中便可应用了,下面的例子即如此.
* */
public class student extends people {
/**
* @param args
*/
private String school;
private String class0;
public student ()
{
}
public student(String school,String class0)
{
this.class0=class0;
this.school=school;
}
public void goToSchool()
{
System.out.print("上学去咯!");
System.out.print(this.getName()+this.getAge()+school+" "+class0);//关键所在,调用父类的私有变量
}
public static void main(String[] args)
{
student s1=new student("第一中学","五年级");
s1.setName("张三");//调用父类的私有变量
s1.setAge(12);//调用父类的私有变量
s1.say();
s1.goToSchool();
}
}