PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 26, 2022

[FIXED] When should i create inner class or inner static class?

 October 26, 2022     java, oop     No comments   

Issue

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());
  }
}

Solution

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();


Answered By - Rubydesic
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing