我可以让一个类只有方法吗?

时间:2015-05-03 20:26:15

标签: java oop

我想为读取,写入,删除和更新等文件操作创建一个类 这个类只有方法

我有这个maindrive

public class HW10 {

    public static void main(String[] args) {

        final String STUDENTS_FILE = "C:\\data\\students.dat";

        RandomAccessFile studentsFile = null ;
        .
        .
        .
        studentsFile = new RandomAccessFile(STUDENTS_FILE, "rw");
        Student student = new Student(1,100,"John","Smith","CIS",3.1) ;
        .
        .
        // write student object to studentsFile
        writeData( studentsFile, student );
        .
        .
        // read from studentsFile
        Student readRecord = new Student() ; 
        studentsFile.seek(0); 
        readData( studentsFile, readRecord );

}

    // read date methods
    private static void readData( RandomAccessFile studentsFile, Student readRecord) 
        { 
         ....   read code
        }
    // write data methods
        private static void writeData( RandomAccessFile studentsFile, Student anItem) 
        { 
        ... write code
        }

如何将readData和writeData方法转换为另一个类,如DataAccessFile,因此DataAccessFile具有类似的所有文件操作

public class DataAccessFile {
    public void writeData(RandomAccessFile studentsFile,Student record){
     .......
    }
  public void readData(RandomAccessFile studentsFile,Student record){
     .....
    }

  public void updateData(RandomAccessFile studentsFile,Student record){
......
}
public void deleteData(RandomAccessFile studentsFile,Student record){
}

}

学生班

public class Student {
    // class attributes
    private int    recordStatus ;
    private int studentID ;
    private String lastName ;
    private String firstName ;
    private String majorCode ;
    private double gpa ;
    public Student(int recordStatus, int studentID, String firstName, String lastName ,String majorCode, double gpa) {
        setRecordStatus(recordStatus) ;
        setStudentID(studentID);
        setLastName(lastName);
        setFirstName(firstName);
        setMajorCode(majorCode);
        setGpa(gpa);
    }

    public Student() {
        setRecordStatus(0) ;
        setStudentID(0);
        setLastName("");
        setFirstName("");
        setMajorCode("");
        setGpa(0);
    }
    // getter
    .
    .
    // setter
    .
    .

}

1 个答案:

答案 0 :(得分:2)

是的,你可以这样做;这样的类通常称为实用程序类。你的DataAccessFile课程是一个好的开始,但也许FileUtils可能是一个更合适的名字。以下是实用程序类的一些一般原则:

  • 上课final;不应该是从实用程序类创建子类的原因。
  • 通过声明构造函数private来使类不可实例化。
  • 制作所有方法static。客户端代码应通过引用class名称来使用该实用程序,例如:FileUtils.writeData(...)