Java——interface练习(Volunteer接口)

(仅记录个人的学习之路)
根据UML图(省略set和get方法),实现Person类、Student类和Volunteer接口的定义。
要求编写用户测试程序:
(1) 创建一个学生对象, 要求使用类常量为grade成员变量赋值;
(2) 从键盘输入姓名和社团信息,并在控制台输出这些信息。
Java——interface练习(Volunteer接口)_第1张图片
示例如下:
Java——interface练习(Volunteer接口)_第2张图片

代码如下:

package Interface;
import java.util.Scanner;
interface Volunteer{
	public String volunteer(String organization) ;
}

class Person{
		private String name;
		public Person() {
		}
		public Person(String name) {
			this.name = name;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String toString() {
			return "姓名:" + name;
		}
}

class Student extends Person implements Volunteer{
	private int grade;
	public static final int FRESHMAN = 1;
	public static final int SOPHOMORE = 2;
	public static final int JUNIOR = 3;
	public static final int SENIOR = 4;
	public Student(String name, int grade) {
		super(name);
		this.grade = grade;
	}
	public int getGrade() {
		return grade;
	}
	public void setGrade(int grade) {
		this.grade = grade;
	}
	public String volunteer(String organization) {
		return organization;
	}
	public String toString() {
		return super.toString() + '\n' + "年级:" + grade;
	}
}

public class Interface {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		Student stu = new Student(input.next(), Student.FRESHMAN);
		System.out.println(stu.toString() + '\n' + "所属社团:" + stu.volunteer(input.next()));
	}
}

运行结果:
Java——interface练习(Volunteer接口)_第3张图片

你可能感兴趣的:(Java——interface练习(Volunteer接口))