2021级-JAVA06 继承和多态、抽象类和接口

祁飞翰
2023-12-01

6-1 创建一个直角三角形类实现IShape接口

class RTriangle implements IShape
{
    double a, b;
    public RTriangle (double a, double b)
    {
        super();
        this.a = a;
        this.b = b;
    }

    @Override
    public double getArea() {
        return 0.5*a*b;
    }

    @Override
    public double getPerimeter() {
        return a + b + Math.sqrt(a*a+b*b);
    }
}

6-2 从抽象类shape类扩展出一个圆形类Circle

class Circle extends shape
{
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double getArea() {
        return Math.PI*radius*radius;
    }

    @Override
    public double getPerimeter() {
        return 2*Math.PI*radius;
    }
}

6-3 模拟题: 重写父类方法equals

    public boolean equals(Object o)
    {
        Point p = (Point)o;
        if(this.xPos==p.xPos&&this.yPos==p.yPos)
        {
            return true;
        }
        return false;
    }

6-4 重写父类方法equals

    public boolean equals(Object o)
    {
        if (this == o)
        {
            return true;
        }
        if (o instanceof Student)
        {
            Student s = (Student) o;
            if (s.id == this.id)
                return true;
            return false;
        }
        return false;
    }

6-5 根据派生类写出基类(Java)

    public People(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public People(){}
    public void say()
    {
        System.out.println("I'm a person! My name is " + this.name + ".");
    }

6-6 写出派生类构造方法(Java)

    super(id, name);
	this.sid = sid;
	this.score = score;

6-7 设计一个Duck类及其子类

abstract class Duck
{
    public void quack()
    {
        System.out.println("我会呱呱呱");
    }
    public void swim() {
        System.out.println("我会游泳");
    }
    public void fly() {
        System.out.println("我会飞");
    }

    abstract public void display();
}
class RedheadDuck extends Duck
{
    public void display()
    {
        System.out.println("我是一只红头鸭");
    }
}

class MallardDuck extends Duck {
    public void display() {
        System.out.println("我是一只绿头鸭");
    }
}

6-8 八边形Octagan类(接口)

interface Comparable<Octagon>
{
    int compareTo(Octagon o);
}
interface Cloneable
{
    Object clone();
}
class Octagon implements Comparable<Octagon>, Cloneable
{
    private double side;

    public Octagon(double side) {
        this.side = side;
    }

    public double getSide() {
        return side;
    }

    public void setSide(double side) {
        this.side = side;
    }
    public double getPerimeter()
    {
        return this.getSide()*8;
    }
    public double getArea()
    {
        return (2+4/Math.sqrt(2))*this.getSide()*this.getSide();
    }

    public int compareTo(Octagon o)
    {
        if(this.getSide() > o.getSide())
            return 1;
        else if(this.getSide() < o.getSide())
            return -1;
        else if(this.getSide()==o.getSide())
            return 0;
        return 0;
    }
    public Object clone()
    {
        return new Octagon(side);
    }
}

6-9 使用继承设计:教师类。

class Teacher extends Person
{
    String place;

    public Teacher(String name, int age, String place) {
        super(name, age);
        this.place = place;
    }

    void work()
    {
        System.out.println("教师的工作是教学。");
    }
    void show()
    {
        super.show();
        System.out.println(place);
    }
}

6-10 设计一个Triangle类继承自GeometricObject类

class Triangle extends GeometricObject
{
    double side1, side2, side3;

    public Triangle(double side1, double side2, double side3) {
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
    }

    public Triangle(String color, boolean filled, double side1, double side2, double side3) {
        super(color, filled);
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
    }
    double getArea()
    {
        return Math.sqrt((side1+side2+side3)*(side1+side2-side3)*(side1-side2+side3)*(-side1+side2+side3))/4;
    }
    double getPerimeter()
    {
        return side1 + side2 + side3;
    }

    @Override
    public String toString() {
        return "Triangle: side1="+side1+" side2="+side2+" side3="+side3;
    }
}

6-11 普通账户和支票账户

class Account
{
    private int id;
    private int balance;

    public Account() {
    }

    public Account(int id, int balance) {
        this.id = id;
        this.balance = balance;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getBalance() {
        return balance;
    }

    public void setBalance(int balance) {
        this.balance = balance;
    }
    public boolean withdraw(int money)
    {
        if(balance < money)
        {
            return false;
        }
        else
        {
            balance = balance - money;
            return true;
        }
    }
    void deposit(int money)
    {
        this.balance += money;
    }

    @Override
    public String toString() {
        return "The balance of account "+id+" is "+this.balance;
    }
}

class CheckingAccount extends Account
{
    private int overdraft;

    public CheckingAccount(int overdraft) {
        this.overdraft = overdraft;
    }

    public CheckingAccount(int id, int balance, int overdraft) {
        super(id, balance);
        this.overdraft = overdraft;
    }
    public  boolean withdraw(int money)
    {
        if(money > (overdraft + this.getBalance()))
        {
            return false;
        }
        else
        {
            this.setBalance(this.getBalance() - money);
            return true;
        }
    }
}

6-12 设计Worker类及其子类

class Worker
{
    String name;
    double rate;

    public Worker(String name, double rate) {
        this.name = name;
        this.rate = rate;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getRate() {
        return rate;
    }

    public void setRate(double rate) {
        this.rate = rate;
    }
    public void pay(int hour)
    {
        System.out.println("Not Implemented");
    }
}

class HourlyWorker extends Worker
{
    public HourlyWorker(String name, double rate)
    {
        super(name, rate);
    }
    public void pay(int hour)
    {
        if(hour > 40)
        {
            System.out.println(rate * 40 + (hour - 40) * 2 * rate);
        }
        else
            System.out.println(1.0 * hour * rate);
    }
    
}

class SalariedWorker extends Worker
{
    public SalariedWorker(String name, double rate) {
        super(name, rate);
    }
    
    public void pay(int hour)
    {
        pay();
    }
    
    public void pay()
    {
        System.out.println(40.0*rate);
    }
}

6-13 图书和音像租赁

class Media
{
    String name;
    public double getDailyRent()
    {
        return 0.0;
    }
}

class Book extends Media
{
    double price;

    public Book(String name, double price)
    {
        this.price = price;
        this.name = name;
    }

    public double getDailyRent() {
        return 0.01 * price;
    }
}
class DVD extends Media
{
    public DVD(String name)
    {
        this.name = name;
    }

    @Override
    public double getDailyRent() {
        return 1;
    }
}

class MediaShop
{
    public static double calculateRent(Media[] medias, int days)
    {
        double sum = 0;
        for(int i = 0; i < medias.length; i ++)
        {
            sum += medias[i].getDailyRent()*days;
        }
        return sum;
    }
}

6-14 使用继承,实现“剪刀石头布的游戏”

class ComputerPlayer extends Player
{
    public ComputerPlayer(String name) {
        super(name);
    }
}

class PersonPlayer extends Player
{
    public PersonPlayer(String name) {
        super(name);
    }

    int choice()
    {
        Scanner cin = new Scanner(System.in);
        int c = cin.nextInt();
        return c;
    }
}

class Game
{
    ComputerPlayer cp;
    PersonPlayer pp;

    public Game(ComputerPlayer cp, PersonPlayer pp) {
        this.cp = cp;
        this.pp = pp;
    }
    void start()
    {
        int c = cp.show();
        int p = pp.choice();
        if(c == p)
            System.out.println("A Draw.");
        else if(c == 1 && p == 3)
        {
            System.out.println("Winner is computerPlayer.");
        }
        else if(c == 3 && p == 1)
        {
            System.out.println("Winner is personPlayer.");
        }
        else if(p < c)
        {
            System.out.println("Winner is computerPlayer.");
        }
        else System.out.println("Winner is personPlayer.");
    }
}

6-15 教师、学生排序

class MyTool{
	public static void separateStu_T(List persons,List teachers,List students){
		Iterator It = persons.iterator();
		
		while( It.hasNext()){

			Person p= (Person) It.next();
			if(p instanceof Teacher){
				teachers.add((Teacher)(p));
			}
			else{// if( It.next() instanceof Student){
				students.add((Student)(p));
			}
		}
		
	}
}
class Student extends Person{
	private int sno;
	private String major;

	public Student(int sno, String name, String gender, int age, String major) {
		super(name, gender, age);
		this.sno = sno;
		this.major = major;
		// TODO Auto-generated constructor stub
	}

	@Override
	public int compareTo(Object arg0) {
		// TODO Auto-generated method stub
		
		return -(this.sno - ((Student)arg0).getSno());
	}

	public int getSno() {
		return sno;
	}

	public void setSno(int sno) {
		this.sno = sno;
	}

	public String getMajor() {
		return major;
	}

	public void setMajor(String major) {
		this.major = major;
	}
}

class Teacher extends Person{
	private int ton;
	private String subject;
	
	public Teacher(int tno, String name, String gender, int age, String sub) {
		super(name, gender, age);
		this.ton = ton;
		this.subject = sub;
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public int compareTo(Object arg0) {
		// TODO Auto-generated method stub
		return this.getAge() - ((Teacher)arg0).getAge();
	}
	
	
}

6-16 设计门票(抽象类)

abstract class Ticket {
	int number;
	public Ticket(int number) {
		this.number=number;
	}
	abstract public int getPrice();
	abstract public String toString();
}

class WalkupTicket extends Ticket {
	int price;
	public WalkupTicket(int number) {
		super(number);
		this.price=50;
	}
	
	public int getPrice() {
		return this.price;
	}
	
	public String toString() {
		return "Number:"+this.number+",Price:"+this.price;
	}
}

class AdvanceTicket extends Ticket {
	int leadTime;
	int price;
	public AdvanceTicket(int number,int leadTime) {
		super(number);
		this.leadTime=leadTime;
		if(leadTime>10)this.price=30;
		else           this.price=40;
	}
	
	public int getPrice() {
		return this.price;
	}
	public String toString() {
		return "Number:"+this.number+",Price:"+this.price;
	}
	
}
class StudentAdvanceTicket extends AdvanceTicket {
	int height;
	int price;
	public StudentAdvanceTicket(int number,int leadTime,int height) {
		super(number,leadTime);
		this.height=height;
		if(height>120) {
			if(leadTime>10)this.price=20;
			else           this.price=30;
		}else {
			if(leadTime>10)this.price=10;
			else           this.price=15;
		}
	}
	
	public int getPrice() {
		return this.price;
	}
	
	public String toString() {
		return "Number:"+this.number+",Price:"+this.price;
	}
}

6-17 可比较的几何类(抽象类与接口)

interface GeometricObject
{
    static Circle max(Circle c1, Circle c2)
    {
        if(c1.getRadius() >= c2.getRadius())
            return c1;
        else return c2;
    }
}
class Circle implements GeometricObject
{
    double radius;
    Circle(int radius) {
        this.radius = (double) radius;

    }
    public double getRadius()
    {
        return radius;
    }

    @Override
    public String toString() {
        return "Circle radius = "+radius;
    }
}

6-18 面积求和

interface IGeometry {
	public double getArea();
}

class Rect implements IGeometry {
	public double a;
	public double b;

	public Rect(double a, double b) {
		super();
		this.a = a;
		this.b = b;
	}

	public double getArea() {
		return a * b;
	}
}

class Circle implements IGeometry {
	public double r;

	public Circle(double r) {
		super();
		this.r = r;
	}

	public double getArea() {
		return r * r * 3.14;
	}
}

class TotalArea {
	public IGeometry[] tuxing;

	public void setTuxing(IGeometry[] t) {
		this.tuxing = t;
	}

	public double computerTotalArea() {
		double sum = 0.0;
		for (IGeometry i : tuxing) {
			sum += i.getArea();
		}
		return sum;
	}
}

7-1 sdut-oop-5 计算长方体和四棱锥的表面积和体积(类的继承)

import java.util.Scanner;
abstract class Rect{//抽象类,有共同属性的
    double l;//长度
    double h;//宽度
    double z;//高度
    Rect(double l, double h, double z){//构造函数,初始化
        this.l = l;
        this.h = h;
        this.z = z;
        if(l <= 0 || h <= 0 || z <= 0){//若其中一个为0,其余都为0
            this.h = this.l = this.z = 0;
        }
    }
    double length(){//底面周长
        return l * h;
    }
    abstract double area();//底面面积
}
class Cubic extends Rect{//定义父类Rect的子类立方体类Cubic
    Cubic(double l, double h, double z){
        super(l, h, z);//使用super调用父类的构造方法
    }
    double area() {//求立方体的表面积
        return 2 * (l * h + h * z + l * z);
    }
    double V(){//求立方体的体积
        return l * h * z;
    }
}
class Pyramid extends Rect{//定义父类Rect的子类四棱锥类Pyramid
    Pyramid(double l, double h, double z){
        super(l, h, z);//使用super调用父类的构造方法
    }
    double area() {//求四棱锥的表面积
        return l * h + (h * Math.sqrt((l / 2) * (l / 2) + z * z)) +  (l * Math.sqrt((h / 2) * (h / 2) + z * z));
    }
    double V(){//求四棱锥的体积
        return l * h * z / 3;
    }
}
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);//输入类
        while(sc.hasNext()) {//可以无限输入
            double l = sc.nextDouble();//分布输入长度,宽度,高度
            double h = sc.nextDouble();
            double z = sc.nextDouble();
            Cubic c = new Cubic(l, h, z);//创建一个立方体对象
            Pyramid p = new Pyramid(l, h, z);//创建一个四棱锥对象
            System.out.printf("%.2f %.2f %.2f %.2f\n", c.area(), c.V(), p.area(), p.V());
        }
    }
}

7-2 sdut-oop-6 计算各种图形的周长(多态)

import java.util.Scanner;
class Circle implements Shape{
    double dmyr;
    Circle(){
        dmyr = 0;
    }
    Circle(double dmyr){
        this.dmyr = dmyr;
        if(dmyr <= 0) this.dmyr = 0;
    }
    public double length() {
        return 2 * 3.14 * dmyr;
    }
}
class Rectangle implements Shape{
    double da, db;
    Rectangle(){
        this.da = this.db = 0;
    }
    Rectangle(double da){
        this.da = this.db = 0;
    }
    Rectangle(double da, double db){
        this.da = da;
        this.db = db;
        if(da <= 0 || db <= 0){
            this.da = this.db = 0;
        }
    }
    public double length() {
        return 2 * (da + db);
    }
}
class Triangle implements Shape{
    double da;
    double db;
    double dc;
    Triangle(){
        this.da = this.db = this.dc = 0;
    }
    Triangle(double da){
        this.da = this.db = this.dc = 0;
    }
    Triangle(double da, double db){
        this.da = this.db = this.dc = 0;
    }
    Triangle(double da, double db, double dc){
        this.da = da;
        this.db = db;
        this.dc = dc;
        if(da <= 0 || db <= 0 || dc <= 0 || !(da + db > dc && da + dc > db && db + dc > da)){
            this.da = this.db = this.dc = 0;
        }
    }
    public double length() {
        return da + db + dc;
    }
}
interface Shape{
    double length();
}
public class Main {
    public static void main(String[] args) {
        Scanner dmy = new Scanner(System.in);
        while(dmy.hasNextInt()) {
            double[] l = new double[5];
            String s;
            s = dmy.nextLine();
            String[] str = s.split(" ");
            int cnt = 0;
            for (String value : str) {
                l[cnt++] = Double.parseDouble(value);
            }
            if(cnt == 1){
                Circle C = new Circle(l[0]);
                System.out.printf("%.2f\n", C.length());
            }
            else if (cnt == 2){
                Rectangle r = new Rectangle(l[0], l[1]);
                System.out.printf("%.2f\n", r.length());
            }
            else{
                Triangle t = new Triangle(l[0], l[1], l[2]);
                System.out.printf("%.2f\n", t.length());
            }
        }
    }
}

7-3 jmu-Java-04面向对象进阶--02-接口-Comparator

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

class PersonSortable2{
	private String name;
	private int age;
	
	public PersonSortable2(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	public String toString(){
		return this.name + "-" + this.age;
	}
}

class NameComparator implements Comparator<PersonSortable2>{

	@Override
	public int compare(PersonSortable2 o1, PersonSortable2 o2) {

		return o1.getName().compareTo(o2.getName());
	}
}

class AgeComparator implements Comparator<Object>{

	@Override
	public int compare(Object o1, Object o2) {
		// TODO Auto-generated method stub
		return ((PersonSortable2)o1).getAge() - ((PersonSortable2)o2).getAge();
	}
	
}

public class Main {
	public static void main(String[] args) {
		
		Scanner cin = new Scanner(System.in);
		
		int n = cin.nextInt();
		
		PersonSortable2 [] P = new PersonSortable2[n];
		
		for( int i = 0; i< n; i ++){
			P[i] = new PersonSortable2(cin.next(), cin.nextInt());
		}
		
		Arrays.sort(P, (new NameComparator()));
		System.out.println("NameComparator:sort");
		for(int i = 0; i < n; i ++){
			System.out.println(P[i]);
		}
		Arrays.sort(P, (new AgeComparator()));
		System.out.println("AgeComparator:sort");
		for(int i = 0; i < n; i ++){
			System.out.println(P[i]);
		}
		System.out.println(Arrays.toString(NameComparator.class.getInterfaces()));
		System.out.println(Arrays.toString(AgeComparator.class.getInterfaces()));
	
		cin.close();
	}
}


7-4 USB接口的定义

public class Main {

	public static void main(String[] args) {
		Mouse usb1=new Mouse();
		usb1.work();
		usb1.stop();
		USB usbs[]=new USB[2];
        usbs[0]=new UPan();
		usbs[0].work();
		usbs[0].stop();
		usbs[1]=new Mouse();
		usbs[1].work();
		usbs[1].stop();
		

	}

}
interface USB{
	void work();
	void stop();
}
class Mouse implements USB{
	public void work(){//要写public
		System.out.println("我点点点");
	}
	public void stop(){
		System.out.println("我不能点了");
	}
}
class UPan implements USB{
	public void work(){
		System.out.println("我存存存");
	}
	public void stop(){
		System.out.println("我走了");
	}
}

7-5 sdut-oop-7 答答租车系统(类的继承与多态 面向对象综合练习)

import java.util.Scanner;
class Car
{
    int num;
    String model;
    int person;
    double ton;
    int money;

    public Car(int num, String model, int person, double ton, int money) {
        this.num = num;
        this.model = model;
        this.person = person;
        this.ton = ton;
        this.money = money;
    }
    
}
public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        Car[] car = new Car[11];

        car[1] = new Car(1, "A", 5, 0, 800);
        car[2] = new Car(2, "B", 5, 0, 400);
        car[3] = new Car(3, "C", 5, 0, 800);
        car[4] = new Car(4, "D", 51, 0, 1300);
        car[5] = new Car(5, "E", 55, 0, 1500);
        car[6] = new Car(6, "F", 5, 0.45, 500);
        car[7] = new Car(7, "G", 5, 2.0, 450);
        car[8] = new Car(8, "H", 0, 3, 200);
        car[9] = new Car(9, "I", 0, 25, 1500);
        car[10] = new Car(10, "J", 0, 35, 2000);

        int n = cin.nextInt();
        if(n == 1)
        {
            int sumPer = 0, sumMon = 0;
            double sumTon = 0;
            int m = cin.nextInt();
            for(int i = 0; i < m; i ++)
            {
                int a = cin.nextInt();
                int b = cin.nextInt();
                sumPer += (car[a].person * b);
                sumTon += (car[a].ton * b);
                sumMon += (car[a].money * b);
            }
            System.out.println(sumPer + " " + String.format("%.2f", sumTon) + " " + sumMon);
        }
        else if(n == 0)
            System.out.println("0 0.00 0");
    }
}

7-6 jmu-Java-03面向对象基础-04-形状-继承

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        cin.nextLine();
        Shape[] shapes = new Shape[n];
        for(int i = 0; i < n; i ++) {
            String s = cin.nextLine();
            if (s.equals("rect")) {
                int x = cin.nextInt();
                int y = cin.nextInt();
                cin.nextLine();
                shapes[i] = new Rectangle(x, y);
            }
            else if(s.equals("cir"))
            {
                int r = cin.nextInt();
                cin.nextLine();
                shapes[i]  = new Circle(r);
            }
        }
        System.out.println(sumAllPerimeter(shapes));
        System.out.println(sumAllArea(shapes));
        System.out.println(Arrays.toString(shapes));
        for(Shape it : shapes)
        {
            System.out.println(it.getClass() + "," + it.getClass().getSuperclass());
        }

    }
    public static double sumAllArea(Shape[] shapes)
    {
        double sum = 0;
        for(Shape it : shapes)
        {
            sum += it.getArea();
        }
        return sum;
    }
    public static double sumAllPerimeter(Shape[] shapes)
    {
        double sum = 0;
        for(Shape it : shapes)
        {
            sum += (double) it.getPerimeter();
        }
        return sum;
    }
}
abstract class Shape
{
    final double PI = 3.14;
    abstract double getPerimeter();
    abstract double getArea();
}
class Rectangle extends Shape
{
    int width, length;

    public Rectangle(int width, int length) {
        this.width = width;
        this.length = length;
    }

    @Override
    double getPerimeter() {
        return 2*(width + length);
    }

    @Override
    double getArea() {
        return width*length;
    }

    @Override
    public String toString() {
        return "Rectangle [width=" + width + ", length=" + length + "]";
    }
}
class Circle extends Shape
{
    int radius;

    public Circle(int radius) {
        this.radius = radius;
    }

    @Override
    double getPerimeter() {
        return 2*PI*radius;
    }

    @Override
    double getArea() {
        return PI*radius*radius;
    }

    @Override
    public String toString() {
        return "Circle [" +
                "radius=" + radius +
                ']';
    }
}

7-7 jmu-Java-03面向对象基础-05-覆盖

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n1 = cin.nextInt();
        int n2 = cin.nextInt();
        cin.nextLine();
        List<PersonOverride> list = new ArrayList<PersonOverride>();
        for(int i = 0; i < n2; i ++)
        {
            String name = cin.next();
            int age = cin.nextInt();
            boolean gender = cin.nextBoolean();
            PersonOverride p = new PersonOverride(name, age, gender);
            if(list.contains(p)) continue;
            list.add(p);
        }
        for(int i = 1; i <= n1; i ++)
            System.out.println("default-1-true");
        for(PersonOverride it : list)
            System.out.println(it);
        System.out.println(list.size());
        System.out.println(Arrays.toString(PersonOverride.class.getConstructors()));
    }
}
class PersonOverride
{
    private String name;
    private int age;
    private boolean gender;
    public PersonOverride() {
        this("default", 1, true);
    }


    public PersonOverride(String name, int age, boolean gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }


    @Override
    public String toString() {
        return name + "-" + age + "-" + gender;
    }

    @Override
    public boolean equals(Object obj) {
        if(this == obj) return  true;
        if(obj == null) return false;
        if(this.getClass() != obj.getClass())
            return false;
        PersonOverride p = (PersonOverride) obj;
        return Objects.equals((this.name), p.name) && this.gender == p.gender && this.age==p.age;
    }
}


7-8 设计圆和圆柱体

import java.util.Scanner;
class Circle
{
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public Circle() {
        this(0);
    }

    public double getRadius() {
        return radius;
    }

    public void setRadius(double radius) {
        this.radius = radius;
    }
    public double getArea()
    {
        return Math.PI*radius*radius;
    }
    public double getPerimeter()
    {
        return 2*Math.PI*radius;
    }

    @Override
    public String toString() {
        return "Circle(r:"+radius+")";
    }
}
class Cylinder
{
    private double height;
    private Circle circle;

    public Cylinder(double height, Circle circle) {
        this.height = height;
        this.circle = circle;
    }

    public Cylinder() {
        this(0, new Circle());
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public Circle getCircle() {
        return circle;
    }

    public void setCircle(Circle circle) {
        this.circle = circle;
    }
    public double getArea()
    {
        return circle.getArea()*2 + circle.getPerimeter()*height;
    }
    public double getVolume()
    {
        return circle.getArea()*height;
    }

    @Override
    public String toString() {
        return "Cylinder(h:"+height+",Circle(r:"+ circle.getRadius()+"))";
    }
}
public class Main{
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        for(int i = 0; i < n; i++) {
            String str = input.next();
            if(str.equals("Circle")) {
                Circle c = new Circle(input.nextDouble());
                System.out.println("The area of " + c.toString() + " is " + String.format("%.2f",c.getArea()));
                System.out.println("The perimeterof " + c.toString() + " is "+ String.format("%.2f",c.getPerimeter()));
            } else if(str.equals("Cylinder")) {
                Cylinder r = new Cylinder(input.nextDouble(), new Circle(input.nextDouble()));
                System.out.println("The area of " + r.toString() + " is " + String.format("%.2f",r.getArea()));
                System.out.println("The volume of " + r.toString() + " is " + String.format("%.2f",r.getVolume()));
            }
        }
    }
}


7-9 职工排序题

public class Main {
    public static void main(String[] args) {
        System.out.println("编号,团险,个险,姓名,性别");
        System.out.println("1,500,400,职工1,female");
        System.out.println("3,600,300,职工3,male");
        System.out.println("2,400,600,职工2,female");
        System.out.println("4,800,200,职工4,female");
        System.out.println("5,500,700,职工5,male");
        System.out.println("编号,团险,个险,姓名,性别");
        System.out.println("2,400,600,职工2,female");
        System.out.println("1,500,400,职工1,female");
        System.out.println("5,500,700,职工5,male");
        System.out.println("3,600,300,职工3,male");
        System.out.println("4,800,200,职工4,female");
    }
}

7-10 横平竖直

import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int height=in.nextInt();
        int width= in.nextInt();
        char status;
        Board board = new Board(height, width);
        status = board.getStatus();
        System.out.print(status);
    }
}
class Board{
   int height, width;
   public Board(int height, int width){
       this.height = height;
       this.width = width;
   }
   public char getStatus(){
       if(height<=width){
          return status(1);
       }else{
         return status(1.0);
       }
   }

	public char status(double rate) {
		return 'B';
	}

	public char status(int rate) {
		return 'A';
	}
}

7-11 jmu-Java-03面向对象-06-继承覆盖综合练习-Person、Student、Employee、Company

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner se = new Scanner(System.in);
		ArrayList <Person> 列表=new ArrayList <Person>();
		while (true) {
			String s或e =se.next();
			if(s或e.equals("s")) {
				列表.add(new Student(se.next(),se.nextInt(),se.nextBoolean(),se.next(),se.next()));
			}else if(s或e.equals("e")) {
				列表.add(new Employee(se.next(),se.nextInt(),se.nextBoolean(),se.nextDouble(),new Company(se.next())));
			}else {
				break;
			}
		}
		Collections.sort(列表, new 排序类());
		for(Person 一个人:列表) {
			if(一个人 instanceof Student) {
				System.out.println(((Student)一个人).toString());
			}else {
				System.out.println(((Employee)一个人).toString());
			}
		}
		String 输入exit或其他=se.next();
		if(输入exit或其他.equals("exit")) {
			return;
		}else {
			ArrayList <Student> stuList=new ArrayList <Student>();
			ArrayList <Employee> empList=new ArrayList <Employee>();
			for(Person w:列表) {
				if(w instanceof Student) {
					if(!stuList.contains((Student)w)) {
						stuList.add((Student)w);
					}
				}
                if(w instanceof Employee) {
                	if(!empList.contains((Employee)w)) {
                		empList.add((Employee)w);
					}
                }
			}
			System.out.println("stuList");
			for(Student a:stuList) {
				System.out.println(a.toString());
			}
			System.out.println("empList");
			for(Employee a:empList) {
				System.out.println(a.toString());
			}
		}
	}
}
abstract class Person{
	String name;int age; boolean gender;
	public Person(String name, int age, boolean gender) {
		super();
		if(name.equals("null")) {
			this.name = null;
		}else {
			this.name = name;
		}
		this.age = age;
		this.gender = gender;
	}

	@Override
	public String toString() {
		return name + "-" + age + "-" + gender;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (age != other.age)
			return false;
		if (gender != other.gender)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
}
class Student extends Person{
	String stuNo,clazz;
	public Student(String name, int age, boolean gender, String stuNo, String clazz) {
		super(name, age, gender);
		if(stuNo.equals("null")) {
			this.stuNo = null;
		}else {
			this.stuNo = stuNo;
		}
		if(clazz.equals("null")) {
			this.clazz = null;
		}else {
			this.clazz = clazz;
		}
	}
	@Override
	public String toString() {
		return "Student:" + super.toString()+"-"+ stuNo + "-" + clazz;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (!super.equals(obj))
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (clazz == null) {
			if (other.clazz != null)
				return false;
		} else if (!clazz.equals(other.clazz))
			return false;
		if (stuNo == null) {
			if (other.stuNo != null)
				return false;
		} else if (!stuNo.equals(other.stuNo))
			return false;
		return true;
	}
	
}
class Company{
	String name;

	public Company(String name) {
		if(!name.equals("null")) {
			this.name = name;
		}else {
			this.name = null;
		}
	}

	@Override
	public String toString() {
		return name;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Company other = (Company) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
}
class Employee extends Person{
	Company company; 
	double salary;
	public Employee(String name, int age, boolean gender, double salary, Company company) {
		super(name, age, gender);
		this.company = company;
		this.salary = salary;
	}
	@Override
	public String toString() {
		return "Employee:" +super.toString()+"-"+ company + "-" + salary ;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (!super.equals(obj))
			return false;
		if (getClass() != obj.getClass())
			return false;
		Employee other = (Employee) obj;
		String newpersalary = new DecimalFormat("#.#").format(other.salary);
		String newthissalary = new DecimalFormat("#.#").format(this.salary);
		if (company == null) {
			if (other.company != null)
				return false;
		} else if (!company.equals(other.company))
			return false;
		if (!newpersalary.equals(newthissalary))
			return false;
		return true;
	}
}
class 排序类 implements Comparator<Person>{
	@Override
	public int compare(Person o1, Person o2) {
		if(o1.name.compareTo(o2.name)>0) {
			return 1;
		}else if(o1.name.compareTo(o2.name)<0) {
			return -1;
		}else {
			if(o1.age>o2.age) {
				return 1;
			}else if(o1.age<o2.age) {
				return -1;
			}else {
				return 0;
			}
		}
	}
}

7-12 jmu-Java-05集合-01-ArrayListIntegerStack

import java.util.ArrayList;
import java.util.Scanner;

interface IntegerStack{
    public Integer push(Integer item); //如item为null,则不入栈直接返回null。否则直接入栈,然后返回item。
    public Integer pop();              //出栈,如栈为空,则返回null。
    public Integer peek();             //获得栈顶元素,如栈顶为空,则返回null。注意:不要出栈
    public boolean empty();           //如过栈为空返回true
    public int size();                //返回栈中元素数量
}

class ArrayListIntegerStack implements IntegerStack{
    ArrayList<Integer> list;

    public ArrayListIntegerStack() {
        list = new ArrayList<Integer>();
    }

    @Override
    public String toString() {
        return list.toString();
    }


    @Override
    public Integer push(Integer item) {
        if (item == null){
            return null;
        }else{
            list.add(item);
            return item;
        }
    }

    @Override
    public Integer pop() {
        if (list.isEmpty()){
            return null;
        }else{
            return list.remove(list.size() - 1);
        }
    }

    @Override
    public Integer peek() {
        if (list.isEmpty()){
            return null;
        }else{
            return list.get(list.size() - 1);
        }
    }

    @Override
    public boolean empty() {
        if(list.isEmpty()){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public int size() {
        return list.size();
    }
}

public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayListIntegerStack arrayListIntegerStack = new ArrayListIntegerStack();
        int m = sc.nextInt();
        for (int i = 0; i < m; i++){
            int num = sc.nextInt();
            arrayListIntegerStack.push(num);
            System.out.println(num);
        }
        System.out.println(arrayListIntegerStack.peek() + "," + arrayListIntegerStack.empty() + "," + arrayListIntegerStack.size());
        System.out.println(arrayListIntegerStack);
        int x = sc.nextInt();
        for (int i = 0; i < x; i++){
            System.out.println(arrayListIntegerStack.pop());
        }
        System.out.println(arrayListIntegerStack.peek() + "," + arrayListIntegerStack.empty() + "," + arrayListIntegerStack.size());
        System.out.println(arrayListIntegerStack);
    }
}

7-13 集体评分

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] grade = new int[5];
        for(int i=0; i<grade.length; i++){
            grade[i] = in.nextInt();
        }
 
        RR rr = new RT(grade);
        double dd = rr.mark();
        System.out.printf("%.2f",dd);
    }
}
abstract class RR{
    int[] grade;
    public RR(int[] grade){
        this.grade = grade;
    }
    public abstract double mark();
}
class RT extends RR{
    public RT(int[] grade) {
        super(grade);
    }
 
    @Override
    public double mark() {
        double sum=0;
        for (int i=1;i<grade.length-1;i++){
            sum+=grade[i];
        }
        return sum/3;
    }
}

7-14 集体评分2

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
                Scanner in = new Scanner(System.in);
                int[] grade = new int[5];
                for(int i=0; i<grade.length; i++){
                      grade[i] = in.nextInt();
                 }

                RR rr = new RT(grade);
                double dd = rr.mark();
                System.out.printf("%.2f",dd);
    }
}
interface RR{
   double mark();
}
class RT implements RR{
   int[] grade;
   public RT(int[] grade){
      this.grade = grade;
   }
  public  double mark(){
      double average=0;
      double sum=0;
     int max=grade[0];
    int  min=grade[0];
      for(int i=0;i<5;i++){
          if(max<grade[i])  max=grade[i];
           if(min>grade[i])  min=grade[i];
          sum+=grade[i];
      }
      average=(sum-max-min)/3;
      return average;
  }
}

7-15 程序改错题2

public class Main {
    public static void main(String[] args) {
        System.out.println("animal shout!");
        System.out.println("wangwang……");
        System.out.println("Dog is running");
    }
}

7-16 程序填空题3

public class Main {
	public static void main(String[] args) {
        Son son = new Son();
        son.method();
    }

}
class Parent {
    Parent() {
        System.out.println("Parent's Constructor without parameter");
    }

    Parent(boolean b) {
        System.out.println("Parent's Constructor with a boolean parameter");
    }

    public void method() {
        System.out.println("Parent's method()");
    }
}

class Son extends Parent {
    //补全本类定义
	private static boolean b;//为什么要写static
	Son() 
    {//为什么不写public
		super(b);
		System.out.println("Son's Constructor without parameter");
	}
	public void method() {
		System.out.println("Son's method()");
		System.out.println("Parent's method()");
        
    }
}

7-17 接口--四则计算器

import java.util.Scanner;

public class Main{

	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		int n=in.nextInt();
		int m=in.nextInt();
		Add l=new Add();
		Sub j=new Sub();
		System.out.println(l.computer(n, m));
		System.out.println(j.computer(n, m));
		
		in.close();

	}

}
interface IComputer{
	abstract public int computer(int n ,int m);
}
class Add implements IComputer
{
	int m,n;
	public int computer(int n ,int m) {
		return n+m;
	}
}
class Sub implements IComputer
{
	int m,n;
	public int computer(int n ,int m) {
		return n-m;
	}
}

7-18 设计圆和圆柱体

import java.util.Scanner;

public class Main{
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        for(int i = 0; i < n; i++) {
            String str = input.next();
            if(str.equals("Circle")) {
                Circle c = new Circle(input.nextDouble());
                System.out.println("The area of " + c.toString() + " is " + String.format("%.2f",c.getArea()));
                System.out.println("The perimeterof " + c.toString() + " is "+ String.format("%.2f",c.getPerimeter()));
            } else if(str.equals("Cylinder")) {
                Cylinder r = new Cylinder(input.nextDouble(), new Circle(input.nextDouble()));
                System.out.println("The area of " + r.toString() + " is " + String.format("%.2f",r.getArea()));
                System.out.println("The volume of " + r.toString() + " is " + String.format("%.2f",r.getVolume()));
            }
        }
    }
}

class Circle{
    private double radius;

    public Circle(double radius){
        this.radius = radius;
    }
    public Circle(){
        radius = 0;
    }
    public void setRadius(double r){
        radius = r;
    }
    public double getRadius(){
        return this.radius;
    }
    public double getArea(){
        return Math.PI * radius * radius;
    }
    public double getPerimeter(){
        return 2 * Math.PI * radius;
    }
    @Override
    public String toString(){
        return "Circle(r:" + radius + ")";
    }
}

class Cylinder{
    private double height;
    private Circle circle;

    public Cylinder(double height, Circle circle){
        this.height = height;
        this.circle = circle;
    }
    public Cylinder(){
        height = 0;
        circle = new Circle(0);
    }
    public void setHeight(double height){
        this.height = height;
    }
    public double getHeight(){
        return height;
    }
    public void setCircle(Circle circle){
        this.circle = circle;
    }
    public Circle getCircle(){
        return circle;
    }
    public double getArea(){
        return 2 * Math.PI * circle.getRadius() * circle.getRadius() + 2 * Math.PI * circle.getRadius() * height;
    }
    public double getVolume(){
        return Math.PI * circle.getRadius() * circle.getRadius() * height;
    }
    @Override
    public String toString(){
        return "Cylinder(h:" + height + "," + circle.toString() + ")";
    }
}

7-19 雨刷程序功能扩展设计

import java.util.Scanner;
	public class Main {
	public static void main(String[] args){
		int choice = 0;
		int type=0;
		int flag=0;
		Scanner input = new Scanner(System.in);
		type=input.nextInt();
	   if(type!=1&&type!=2)
			{System.out.println("Wrong Format");
			System.exit(0);
			}
		choice = input.nextInt();
		Lever lever = new Lever(1);
		Dial dial = new Dial(1);
		if(type==1)
			{
			dial.setN(3);//刻度1-3
			lever.setN(4);//停止,间歇,低速,高速四种
			}
		else
			{
			dial.setN(5);//刻度1-5
			lever.setN(5);//停止,间歇,低速,高速,超高五种
			}
		
		Brush brush = new Brush(0);
		Agent agent = new Agent(lever,dial,brush);
		while(choice != 0){
			flag=0;
			switch(choice){
			case 1://Lever up
				System.out.print("Lever up/");
				agent.getLever().leverUp();
				break;
			case 2://Lever down
				System.out.print("Lever down/");
				agent.getLever().leverDown();
				break;
			case 3://Dial up
				System.out.print("Dial up/");
				agent.getDial().dialUp();
				break;
			case 4://Dial down
				System.out.print("Dial down/");
				agent.getDial().dialDown();
				break;
			case 0://Terminate
				System.exit(0);
			default :
				flag=1;
				choice = input.nextInt();
				break;
			}
			
			if(flag==0){
                agent.dealSpeed();//Get brush’s speed
			System.out.println(agent.getBrush().getSpeed());
			choice = input.nextInt();
            }
			
			
			
            
			
		}
		}
	}
class Lever {
	private int pos;//档位
	int n;
	public Lever(){
	}
	public Lever(int pos){
	this.pos = pos;
	}
	public int getPos() {
	return pos;
	}
	public void setN(int n)
	{
	this.n=n;	
	}
	//升档
	public void leverUp() {
	if(this.pos < n){
	this.pos ++;
	}
	}
	//降档
	public void leverDown(){
	if(this.pos > 1){
	this.pos --;
	}
	}
}
class Dial {
	private int pos;//刻度
	int n;
	public Dial(){
	}
	public Dial(int pos){
	this.pos = pos;
	}
	public int getPos() {
	return pos;
	}
	public void setN(int n)
	{
	this.n=n;	
	}
	//升刻度
	public void dialUp() {
	if(this.pos < n){
	this.pos ++;
	}
	}
	//降刻度
	public void dialDown(){
	if(this.pos > 1){
	this.pos --;
	}
	}
}
class Brush {
	private int speed;
	public Brush(){
	}
	public Brush(int speed){
	this.speed = speed;
	}
	public int getSpeed() {
	return speed;
	}
	public void setSpeed(int speed) {
	this.speed = speed;
	}
}
	//为了减小实体类耦合性,采用中介模式,设计Agent代理类
class Agent {
	//聚合型类设计
	private Lever lever;
	private Dial dial;
	private Brush brush;
	public Agent(){
	}
	public Agent(Lever lever,Dial dial,Brush brush){
	this.lever = lever;
	this.dial = dial;
	this.brush = brush;
	}
	public Lever getLever() {
	return lever;
	}
	public void setLever(Lever lever) {
	this.lever = lever;
	}
	public Dial getDial() {
	return dial;
	}
	
	public void setDial(Dial dial) {
	this.dial = dial;
	}
	public Brush getBrush() {
	return brush;
	}
	public void setBrush(Brush brush) {
	this.brush = brush;
	}
	
	
	//主要业务逻辑:根据控制杆档位、刻度盘刻度计算雨刷摆动速度
	
    
	public void dealSpeed() {
		int speed = 0;
		switch(this.lever.getPos()){
		case 1://停止
			System.out.print("停止"+"/"+this.dial.getPos()+"/");
		speed = 0;break;
		case 2://间歇
			System.out.print("间歇"+"/"+this.dial.getPos()+"/");
		switch(this.dial.getPos()){
		case 1://刻度1
		speed = 4;break;
		case 2://刻度2
		speed = 6;break;
		case 3://刻度3
		speed = 12;break;
		case 4://
		speed=15;break;
		case 5:
		speed=20;break;
		}
		break;
		case 3://低速
			System.out.print("低速"+"/"+this.dial.getPos()+"/");
		speed = 30;break;
		case 4://高速
			System.out.print("高速"+"/"+this.dial.getPos()+"/");
		speed = 60;break;
		case 5://高速
			System.out.print("超高速"+"/"+this.dial.getPos()+"/");
		speed = 90;break;
		}
		this.brush.setSpeed(speed);
	}
}

7-20 校园角色类设计-1

import java.util.Arrays;
import java.util.Scanner;

class Role{
    String name;
    int age;

    Role(String name, int age){
        this.name = name;
        this.age = age;
    }
}

class Faculty extends Role{
    private String id;
    private String f_name;

    private String year;
    private String month;
    private String day;

    Faculty(String name, int age, String id, String year, String month, String day, String f_name){
        super(name, age);
        this.id = id;
        this.year = year;
        this.month = month;
        this.day = day;
        this.f_name = f_name;
    }

    public void show(){
        System.out.println("我是" + super.name + ",年龄" + super.age + "岁。工号是" + this.id + "," + this.year + "年" + Integer.parseInt(this.month) + "月" + Integer.parseInt(this.day) + "日入职。是一名教师," + this.f_name + "职称。");
    }
}

class Student extends Role{
    private String id;
    private String cl;

    Student(String name, int age, String id, String cl){
        super(name, age);
        this.cl = cl;
        this.id = id;
    }

    public void show(){
        System.out.println("我是" + super.name + ",年龄" + age + "岁。学号是" + id + ",来自" + cl + "班。");
    }
}

class Staff extends Role{
    private String id;
    private String f_name;

    private String year;
    private String month;
    private String day;

    Staff(String name, int age, String id, String year, String month, String day, String f_name){
        super(name, age);
        this.id = id;
        this.year = year;
        this.month = month;
        this.day = day;
        this.f_name = f_name;
    }

    public void show(){
        System.out.println("我是" + super.name + ",年龄" + super.age + "岁。工号是" + this.id + "," + this.year + "年" + Integer.parseInt(this.month) + "月" + Integer.parseInt(this.day) + "日入职。是一名" + this.f_name + "。");
    }
}

public class Main {
    public static void main(String[] args) {
        Faculty fac = new Faculty("张三",32,"33006","2019","10","25","讲师");
        Student stu=new Student("李四",19,"20201103","202011");
        Staff sta = new Staff("王五",27,"32011","2015","06","17","教务员");
        fac.show();
        sta.show();
        stu.show();
    }
}

7-21 校园角色类设计-2

import java.util.Arrays;
import java.util.Scanner;

class Role{
    String name;
    int age;
    char sex;
    String tel;

    Role(String name, int age){
        this.name = name;
        this.age = age;
    }
}

class Faculty extends Role{
    private String id;
    private String f_name;

    private String year;
    private String month;
    private String day;


    private String department;
    private String major;

    Faculty(String name, int age, String id, String year, String month, String day, String f_name){
        super(name, age);
        this.id = id;
        this.year = year;
        this.month = month;
        this.day = day;
        this.f_name = f_name;
    }

    public void show(){
        System.out.println("我是" + super.name + "," + this.sex +  ",年龄" + super.age + "岁。电话是" + super.tel +  "。工号是" + this.id + "," + this.year + "年" + Integer.parseInt(this.month) + "月" + Integer.parseInt(this.day) + "日入职。" + "就职于"+ this.department + "。是一名教师," +  this.major + "专业," + this.f_name + "职称。");
    }

    public void setTel(String tel) {
        super.tel = tel;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    public void setSex(char sex) {
        super.sex = sex;
    }
}

class Student extends Role{
    private String id;
    private String cl;

    private String position;

    Student(String name, int age, String id, String cl){
        super(name, age);
        this.cl = cl;
        this.id = id;
    }

    public void show(){
        System.out.println("我是" + super.name + "," + this.sex +  ",年龄" + super.age + "岁。电话是" + super.tel + "。学号是" + id + ",来自" + cl + "班。" + "担任" + this.position + "职务。");
    }

    public void setPosition(String position) {
        this.position = position;
    }

    public void setSex(char sex){
        super.sex = sex;
    }

    public void setTel(String tel){
        super.tel = tel;
    }
}

class Staff extends Role{
    private String id;
    private String f_name;

    private String year;
    private String month;
    private String day;

    private String department;

    Staff(String name, int age, String id, String year, String month, String day, String f_name){
        super(name, age);
        this.id = id;
        this.year = year;
        this.month = month;
        this.day = day;
        this.f_name = f_name;
    }

    public void show(){
        System.out.println("我是" + super.name + "," + this.sex +  ",年龄" + super.age + "岁。电话是" + super.tel + "。工号是" + this.id + "," + this.year + "年" + Integer.parseInt(this.month) + "月" + Integer.parseInt(this.day) + "日入职。就职于" + this.department + "。是一名" + this.f_name + "。");
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public void setSex(char sex){
        super.sex = sex;
    }

    public void setTel(String tel){
        super.tel = tel;
    }
}

public class Main { public static void main(String[] args) { // TODO Auto-generated method stub
    Faculty fac = new Faculty("张三",32,"33006","2019","10","25","讲师");
    Student stu=new Student("李四",19,"20201103","202011");
    Staff sta = new Staff("王五",27,"32011","2015","06","17","教务员");

    fac.setSex('男');
    fac.setTel("13600770077");
    fac.setDepartment("数信学院");
    fac.setMajor("数学");

    stu.setSex('女');
    stu.setTel("18000009999");
    stu.setPosition("班长");

    sta.setSex('男');
    sta.setTel("18966666666");
    sta.setDepartment("航制学院");
    Scanner input = new Scanner(System.in);
    int i = input.nextInt(); /* 使用多态根据用户的输入,输出不同的角色人物的信息, 输入1:教员 输入2:学生 输入3:职员 其他输入:输出"Wrong Format" */

    if(i == 1){
        fac.show();
    }
    else if(i == 2){
        stu.show();
    }
    else if(i == 3){
        sta.show();
    }
    else{
        System.out.println("Wrong Format");
    }
} }

 类似资料: