首页 > 解决方案 > java中如何创建私有数组并通过main方法访问?

问题描述

我想在公共类之外但在同一个文件中创建一个类,并且在该类中我想创建一个私有数组,该数组只能通过以前的公共类创建对象来访问。我还想通过公共类将数据存储到该数组中。

标签: java

解决方案


我建议你开始学习java,这样你下次就不用问这种问题了。目前,您可以在下面的示例中找到如何实现您所要求的:

public class Learning {
    public static void main(String[] args) {
        Course course = new Course();
        List<String> materials = new ArrayList<>();
        materials.add("java basic courses");
        materials.add("OOP courses");
        
        // here we use setters to set course materials and notes
        course.setMaterials(materials);
        course.setNotes(new int[] {19,20});

        System.out.println("Display course materials");
        for (String material : course.getMaterials()) {
            System.out.println("Material : " + material);
        }

        System.out.println("Display Notes");
        for (int note : course.getNotes()) {
            System.out.println("Note : " + note);
        }
    }
}

class Course {

    private List<String> materials;
    private int[] notes;


    public List<String> getMaterials() {
        return materials;
    }

    public void setMaterials(List<String> materials) {
        this.materials = materials;
    }

    public int[] getNotes() {
        return notes;
    }

    public void setNotes(int[] notes) {
        this.notes = notes;
    }
}

推荐阅读