Java 类和对象

一个类以public class 开头,类名必须和文件名一致,public class代表这个类是公共类,可以随意调用,public class后紧跟类名。类也叫做自定义类型,程序中不能出现相同名字的类。
类体中可以定义这个类的属性的变量,称之为成员变量。

public class Phone {
    Screen screen;
    Mainboard mainboard;
    double price;
    boolean hasFigurePrintUnlocker;

    Phone prePhone;
}

使用new操作符可以创建一个类的实例/对象(instance/object),new创建了一个对象之后,类中创建的变量都会被赋予与其类型相对应初始值。用点操作符来访问实体的属性。

public class MyPhoneMaker {
    public static void main(String[] args) {
        Phone phone = new Phone();

        phone.hasFigurePrintUnlocker = true;
        phone.price = 1999;
        phone.screen = new Screen();

        phone.screen.producer = "京东方";
        phone.screen.size = 8.8;


        CPU cpu = new CPU();
        cpu.producer = "三星";
        cpu.speed = 3.5;

        Memory memory = new Memory();
        memory.producer = "三星";
        memory.capacity = 4;

        Storage storage = new Storage();
        storage.producer = "Intel";
        storage.capacity = 128;

        phone.mainboard = new Mainboard();

        phone.mainboard.cpu = cpu;
        phone.mainboard.memory = memory;
        phone.mainboard.storage = storage;

        phone.mainboard.model = "EA888";
        phone.mainboard.year = 2019;

        phone.prePhone = new Phone();
    }
}

你可能感兴趣的:(Java 类和对象)