/*继承的原则就是子类继承父类的成员属性,包括实例成员变量和类成员变量。 子类也可以继承除构造方法之外的所有成员方法,包括实例成员方法和类成员方法。*/
/* PrimarySchool类*/
public class PrimarySchool {
String name;
int age;
String sex;
int courseOfCount;
PrimarySchool(){
}
PrimarySchool(String name,String sex){
this.name=name;
this.sex=sex;
}
PrimarySchool(String name,int age,String sex,int courseOfCount){
this.name=name;
this.age=age;
this.sex=sex;
this.courseOfCount=courseOfCount;
}
String setName(String name) {
return name;
}
String setSex(String sex) {
return sex;
}
int setAge(int age) {
return age;
}
int setcourseOfCount(int courseOfCount) {
return courseOfCount;
}
void speak(){
System.out.println("我是一名小学生"+'\n'+"我的名字叫:"+name+'\n'+"我今年"+age+"了!"
+"是个可爱的"+sex+"孩子!"+'\n'
+ "我每天要学习"+courseOfCount+"门功课!");
}
}
/* MiddleSchool类*/
public class MiddleSchool extends PrimarySchool{
void speak(){
/*子类方法的重写,子类不能继承父类的构造方法*/
System.out.println("我是一名中学生"+'\n'+"我的名字叫:"+name+'\n'+"我今年"+age+"了!"
+"是个可爱的"+sex+"孩子!"+'\n'
+ "我每天要学习"+courseOfCount+"门功课!");
}
MiddleSchool(String name,String sex){
/*子类虽然不能继承父类的构造函数,但可以通过super来调用*/
super(name,sex);
}
}
/* HightSchool类*/
public class HightSchool extends MiddleSchool{
boolean girlFriend;
HightSchool(String name, String sex) {
super(name, sex);
}
boolean yesOrNo() {
return girlFriend;
}
void speak() {
System.out.println("你好呀!"+'\n'+"我现在是个高中生了!");
}
/*方法的重载*/
void speak(boolean girlFriend)
{
if(girlFriend==true){
System.out.println("我已经有一个女朋友了,耶!");
}
else{
System.out.println("不谈女友,我们还是朋友!");
}
}
}
/*GradeTest测试类*/
public class GradeTest {
public static void main(String args[]) {
PrimarySchool primary=new PrimarySchool("小明",5,"男",4);
primary.speak();
System.out.println();
/*修改信息,重新设值*/
primary.name=primary.setName("小红");
primary.sex=primary.setSex("女");
primary.speak();
System.out.println();
/*子类的继承,方法的重写(方法的覆盖)*/
MiddleSchool middle=new MiddleSchool("小明","男");
middle.age=middle.setAge(11);
middle.courseOfCount=middle.setcourseOfCount(8);
middle.speak();
System.out.println();
/* */
HightSchool hight = new HightSchool("小明","男");
hight.speak();
hight.speak(true);
}
}