public class Laptop {
    private char color;
    private int cpuModel;

    // 无参构造方法
    public Laptop() {
    }

    // 有参构造方法
    public Laptop(char color, int cpuModel) {
        this.color = color;
        this.cpuModel = cpuModel;
    }

    // 输出笔记本信息的方法
    public void printInfo() {
        System.out.println('颜色:' + color);
        System.out.println('CPU型号:' + cpuModel);
    }
}

public class TestLaptop {
    public static void main(String[] args) {
        // 创建无参构造方法的对象
        Laptop laptop1 = new Laptop();
        laptop1.printInfo();

        System.out.println("------------------");

        // 创建有参构造方法的对象
        Laptop laptop2 = new Laptop('黑', 1234);
        laptop2.printInfo();
    }
}

原文地址: https://www.cveoy.top/t/topic/pNuO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录