创建继承于类person的类student

package dan;

class Person{//创建Person
    String name;//定义变量name
    String sex;//定义变量
    int age;//定义变量

    void getInfo(String n,String s,int a){//定义getInfo()
        name=n;//获取name的信息
        sex=s;//获取sex的信息
        age=a;//获取age的信息
    }
    void showInfo(){//定义showInfo
        System.out.println("姓名:"+name);//输出name的信息
        System.out.println("性别:"+sex);
        System.out.println("年龄:"+age);
    }

}

public class student extends Person{//定义子类Student继承父类Person,(若这里不用extends Person,下面name,sex,age将因找不到路径而显示错误,需重新定义)
    int id;//定义变量
    String school;
    void setInfo(int num,String school_name){//定义setInfo()
        id=num;//将num赋值给id
        school=school_name; 
    }
    void outputInfo(){//定义outputInfo
        System.out.println("学校:"+school);//显示school信息
        System.out.println("学号:"+id);
        System.out.println("姓名:"+name);
        System.out.println("性别:"+sex);
        System.out.println("年龄:"+age);

    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("第一个人的信息:");
        student zhang=new student();//实例化
        zhang.name="张力";
        zhang.sex="男";
        zhang.age=18;
        zhang.id=01;
        zhang.school="dsfgf";
        zhang.showInfo();//调用父类的showInfo(),输出姓名性别年龄
        System.out.println();//空行
        zhang.outputInfo();//调用子类的outputInfo(),输出zhang的全部信息
        System.out.println("第二个人的信息:");
        student li=new student();//实例化
        li.getInfo("沥沥","女",18);
        li.setInfo(02,"sfjn");
        li.outputInfo();//调用outputInfo()
    }
}

运行结果:
创建继承于类person的类student_第1张图片

知识点:1.继承的实现
2.父类和子类

你可能感兴趣的:(创建继承于类person的类student)