问题 B: 继承 II

题目描述



编写Person类
包含成员方法:       String name;         int age; 
包含成员变量:  show();
      构造方法:  Person(String name, int age);

=========================================
编写Student类(继承Person类)
包含构造方法:   Student (String dep, String name, int age)
包含成员变量:   String department;

Main类已经编写好。

import java.util.*;
public class Main
{
  public static void main(String[] args)
  { 
    Scanner r = new Scanner(System.in);
    String dep;
    String name;
    int age;
    dep = r.next(); 
    name = r.next();
    if( !r.hasNextInt() )  
          return;
    age = r.nextInt(); 
    if( age < 0 )  
         return;
    Person stu1=new Student(dep,name,age);
    stu1.show();
  }
}

输入

输入院系名字、学生姓名、年龄

输出

输出详见样例

样例输入

Computer Obama 42

样例输出

called the constructor of Person class
I am a student from the department of Computer
called the constructor of Student class: Student(String name,int age,String dep)
Name:Obama  Age: 42

代码:

class Person{
	protected String name;
	protected int age;
	public Person() {
		System.out.println("called the constructor of Person class");
	}
	public Person(String name, int age) {
		this();
		this.name = name;
		this.age = age;
	}
	public void show() {
		System.out.println("Name:"+name+"  Age: "+age);
	}
}
class Student extends Person{
	private String department;
	public Student (String dep, String name, int age) {
		super(name,age);
		this.department = dep;
		System.out.println("I am a student from the department of "+department);
		System.out.println("called the constructor of Student class: Student(String name,int age,String dep)");
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值