Home > OS >  When should i create inner class or inner static class?
When should i create inner class or inner static class?

Time:10-09

I am aware about the static keyword, but in short. My attempt is to create inner static class since it's related to outer class. The practical problem is I am confused how to access it. My reason use static class is that I just need one instance of it per application?

Please correct if you found any misconseption, and give real usage of the class / static class.

public class DbPredecessorTest {
  List<Book> db;
  Book book;
  Integer numberOfBooks;
  static BufferedReader reader;

  static {
    try {
      reader = new BufferedReader(new FileReader(Main.fileLoc));
    } catch (FileNotFoundException e) {
      throw new RuntimeException(e);
    }
  }

  static class Helper {
    DbPredecessor dbPredecessor= new DbPredecessor();
    Long getLines() {
      return reader.lines().count();
    }
  }

My directionless attempt:

class SomeTest {
  @Test
  void ableToSave() throws IOException {
    db.add(book);
    boolean save = Helper.dbPredecessor.save(db);
    assertEquals(true, save);
  }
  @Test
  void save_should_increaseLine() throws IOException {
    db.add(book);
//    numberOfBooks= (int) Helper.get
    boolean save = dbPredecessor.save(db);
    assertEquals(numberOfBooks 1, reader.lines().count());
  }
}

CodePudding user response:

That's not the reason to use a static inner class. A static inner class is functionally an ordinary Java class, the only real reason you would have one is to indicate it's related to the outer class in some way or to make it private.

You could just use a normal static method here:

public class DbPredecessorTest {
    static long getLines() {
      return reader.lines().count();
    }
}

and then use it like so:

long numberOfBooks = DbPredecessorTest.getLines();
  • Related