基类和派生类小程序--简单

import java.util.Scanner;

class Person

{

  private String name;

  private int age;

  public Person()

  {

    System.out.println("调用了Person类的无参数构造方法");

  }

  public Person(String name,int age)

  {

    System.out.println("调用了Person类的有参数构造方法");

    this.name=name;

    this.age=age;

  }

  public void show()

  {

    System.out.println("姓名:"+name+"   年龄:"+age);

  }

}

class Student extends Person  //Student是子类

{

  private String department;

  public Student()

  {

    System.out.println("调用了学生类的无参数构造方法Student()");

  }

  public Student(String name,int age,String dep)

  {

    super(name,age);

    department=dep;

    System.out.println("我是"+department+"的学生");

    System.out.println("调用了学生类的有参数构造方法Student(String name,int age,String dep)");

  }

}

public class App8_2 {

  public static void main(String[] args)

  {

    String sname,dept;

    int age;

    Student stu1=new Student();

    Scanner reader=new Scanner(System.in);

    System.out.print("请输入姓名,年龄和所在的系:");

    sname=reader.next();

    age=reader.nextInt();

    dept=reader.next();

    //Student stu2=new Student("李小四",23,"信息系");

    Student stu2=new Student(sname,age,dept);

    stu1.show();

    stu2.show();

     reader.close()

  }

}

运行结果:

原文地址:https://www.cnblogs.com/duanqibo/p/11133925.html