Java继承练习(2) (2024.7.9)

时间:2024-07-11 07:04:46

        手机类

package Phone20240709;

public class Phone {
    private String brand;
    private String price;
    private static int size;

    public Phone() {}

    public Phone(String brand, String price) {
        this.brand = brand;
        this.price = price;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public static int getSize() {
        return size;
    }

    public static void setSize(int size) {
        Phone.size = size;
    }

    public void call() {
        System.out.printf("价值%s的%d英寸%s手机正在打电话\n", this.price,
                Phone.size, this.brand);
    }

    public void sendMessages() {
        System.out.printf("价值%s的%d英寸%s手机正在发短信\n", this.price,
                Phone.size, this.brand);
    }
    public void playGames() {
        System.out.printf("价值%s的%d英寸%s手机正在玩游戏\n", this.price,
                Phone.size, this.brand);
    }
}

        测试

package Phone20240709;
import java.util.Scanner;
import java.util.ArrayList;
public class PhoneTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<Phone> phonesList = new ArrayList<>();
        System.out.println("要录入多少手机?");
        Phone.setSize(6);
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            System.out.printf("请输入第%d类手机品牌\n", i + 1);
            String brand = sc.next();
            System.out.printf("请输入第%d类手机的价格\n", i + 1);
            String price = sc.next();
            Phone p = new Phone();
            p.setBrand(brand);
            p.setPrice(price);
            phonesList.add(p);
            System.out.println(brand + "手机成功录入");
        }
        showWays(phonesList);
    }

    public static void showWays(ArrayList<Phone> phonesList){
        for (int i = 0; i < phonesList.size(); i++) {
            phonesList.get(i).call();
            phonesList.get(i).sendMessages();
            phonesList.get(i).playGames();
        }
    }

}