Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

Код на java. Есть класс computer, добавьте поля (процессора, тип системы, память) и…

  1. User

    Код на java. Есть класс computer, добавьте поля (процессора, тип системы, память) и иницилизируйте их в Main

  2. Assistant

    class Computer { private String processor; private String systemType; private int memory;

    public String getProcessor() {
        return processor;
    }
    
    public void setProcessor(String processor) {
        this.processor = processor;
    }
    
    public String getSystemType() {
        return systemType;
    }
    
    public void setSystemType(String systemType) {
        this.systemType = systemType;
    }
    
    public int getMemory() {
        return memory;
    }
    
    public void setMemory(int memory) {
        this.memory = memory;
    }
    

    }

    public class Main { public static void main(String[] args) { Computer computer = new Computer(); computer.setProcessor("Intel Core i5"); computer.setSystemType("64-bit"); computer.setMemory(8);

        System.out.println("Processor: " + computer.getProcessor());
        System.out.println("System type: " + computer.getSystemType());
        System.out.println("Memory: " + computer.getMemory() + "GB");
    }
    

    }

  3. User

    Намного намного легче и меньше код

  4. Assistant

    Действительно, можно еще более сократить код. Например, воспользоваться сокращенной формой инициализации полей при объявлении объекта:

    public class Computer {
        public String processor;
        public String systemType;
        public int memory;
    
        public Computer(String processor, String systemType, int memory) {
            this.processor = processor;
            this.systemType = systemType;
            this.memory = memory;
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Computer computer = new Computer("Intel Core i5", "64-bit", 8);
    
            System.out.println("Processor: " + computer.processor);
            System.out.println("System type: " + computer.systemType);
            System.out.println("Memory: " + computer.memory + "GB");
        }
    }
    

    В данном случае, в конструкторе класса Computer происходит инициализация полей, а в Main мы сразу создаем объект с нужными значениями. А чтобы обратиться к полю, мы используем простую форму обращения (например, computer.processor).