General Naming guideline

  • Classes named after nouns:
    • an entity that makes sense in your problem domain.
    • Examples: Printer, Controller, Mailbox, Manager, Handler
  • Interfaces as adjectives:
    • a capability or characteristic of an entity implementing said interface.
    • Examples: Iterable, Serializable, Secured, Asynchronous
  • Methods as verbs or in some cases, adverbs or adverbial clauses:
    • to describe an action
    • Examples: execute, deliver, validate
  • Packages as a grouping of things that make sense to be together (again, this is very strongly tied to your problem domain)

Class Name and public class

  • There can only be one public top-level class per .java file, and public top-level classes must have the same name as the source file.
  • Since we can have non-public classes, we can write something like this in single file:
import java.util.List;
// cannot make Node class as public
// if it is public then it should match the filename
class Node {
    public int val;
    public List<Node> neighbors;
}
 
public class App {
    public static void main(String[] args) throws Exception {
        Node node = new Node();
        node.val = 3;
 
        Node node2 = new Node();
        node2.val = 7;
        node.neighbors = List.of(node2);
        System.out.println(node.val + " " + node.neighbors.get(0).val);
        // 3 7
    }
}

Package Name

  • There is no restriction on package names in java.
  • Unlike public class in a file, you can name whatever package you want even though the folder name or path is different
  • Conventions:
    • Lower case characters only
    • There should be only one English word after each dot.
    • No underscores

Packages

  • Provide namespace
  • Provide access protection via package-private modifier

Auto Import

  • java.lang package is automatically imported