weixin_58683688
2021-06-23 11:16
采纳率: 85.7%
浏览 24

Java类与对象,构造方法,成员变量

按以下要求编程

 

    (1)创建一个Person类,具有成员变量:姓名,年龄,两个重载的构造方法(一个参数为空,一个为两个参数)为成员变量初始化。

 

    (2)再创建两个类Student和Teacher,均继承于Person类,其中Student类增加了班级和学号,Teacher类增加了工号和所属学院,分别定义构造方法设置相应成员变量的信息,并重写toString方法输出相应的信息。

 

    (3)创建测试类测试结果并输出。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • guwei4037 2021-06-23 11:30
    已采纳
    public class Person {
    	private String name;
    	private int age;
    	
    	public Person() {
    		
    	}
    	
    	public Person(String name,int age) {
    		this.name = name;
    		this.age = age;
    	}
    	
    	@Override
    	public String toString() {
    		return "姓名:"+name+",年龄:"+age;
    	}
    }
    
    public class Student extends Person{
    	private String className;
    	private int num;
    	
    	public Student(String name,int age,String className,int num) {
    		super(name,age);
    		this.className = className;
    		this.num = num;
    	}
    	
    	@Override
    	public String toString() {
    		return super.toString()+ ",班级:"+className+",学号:"+num;
    	}
    }
    
    public class Teacher extends Person{
    	private int jobNum;
    	private String college;
    	
    	public Teacher(String name,int age,int jobNum,String college) {
    		super(name,age);
    		this.jobNum = jobNum;
    		this.college = college;
    	}
    	
    	@Override
    	public String toString() {
    		return super.toString()+",工号:"+jobNum+",学院:"+college;
    	}
    }
    
    public static void main(String[] args) {
    		// TODO Auto-generated method stub
    
    		Person student = new Student("张三",16,"高三1班",23);
    		Person teacher = new Teacher("李四",45,1697,"xxx高级中学");
    		
    		System.out.println(student.toString());
    		System.out.println(teacher.toString());
    	}
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题