Java 概念/算法/设计模式 复习

面试中除了做题目,还有一些口头的交流是关于概念、算法对比、设计模式以及语言细节的,这里对 Java 部分做一个简单的总结。因为是在美国这边找工作比较需要,所以主要是英文为主。


概念

这一部分主要是 Java 中基本的概念以及常见的数据结构对比

Object Oriented

  • model organized around objects rather than actions and data rather than logic
  • based on the concept of “objects”
  • contain data in the form of fields(attributes)
  • code in the form of procedures(methods)
  • object’s procedures can access and modify the data fields of the associated object

OOP

  • polymorphism

    • define more than one function with the same name
    • compile time polymorphism(overloading) and runtime polymorphism(overriding)
    • method override: a class method has same name and signature as a method in parent class, JVM determines the proper method to call at runtime
    • method overloading: method with same name but different signature, determined at compile time
  • inheritance

    • allow a child class to inherit some properties from its parent class
    • use extends keyword
    • only public and protected access modifiers can be accessed in child class
  • multiple inheritance

    • Java does not support multiple inheritance
    • diamond problem
    • use of multiple interfaces (or extend a class and implement some interfaces)

      interface A{
      add();
      }
      interface B{
      add();
      }
      class C implements A,B{
      add();
      }
  • abstraction

    • convert real world objects in terms of class
  • encapsulation

    • achieved by combining the methods and attribute into a class
    • class acting like a container encapsulation the properties
    • hide how things work and expose the user requests

Java Keywords

Access modifiers

modifier access in same package access in different package
private no no
public yes yes
default yes no
protected yes only if extend class
  • final keyword

    • can be assigned to variable, method, class, object
    • if assigned
      • variable: behave like a constant and cannot change value
      • method: cannot be overridden in its child class
      • class: no other class can extend it
      • object: only instantiated once
  • synchronized keyword

    • provide lock on the object and prevent race condition
    • can be applied to static/non-static methods or block of code
    • only one thread at a time can access synchronized methods
    • if multiple threads, need to wait for execution complete
  • volatile keyword

    • volatile variable stored in main memory
    • every thread can access
    • local copy updated from main memory
    • has performance issues
  • static variable

    • static cannot be used for class
    • everything declared as static is related to class not object
    • multiple objects of a class share the same instance of static variable
  • static method

    • can be accessed without creating the objects
    • use class name to access static method
    • static method can only access static var