content
- class and object
- interface and implementation
- inheritance and encapsulation
- immutable object
- Generics
class and object
General Concepts and Questions
- Member variables of the class --> object state
Class member function --> object behavior
- The static variables of the class, the static function of the class --> no this reference, the only one in the world
- Ordinary functions refer to static variables, static functions? correct
- Objects refer to static variables and static functions? compile warning
- Static functions refer to ordinary member variables, functions? Compilation error because can't get this reference
special functions of objects
- Constructor: no return value, return itself
- equals: Equivalent to (==), generally need to be rewritten
- hashCode: a.equals(b) can deduce that a.hashCode( ) == b.hashCode( ), and vice versa, because sometimes the hashCode values of different objects will be equal
- toString: Override
interface
compared to class
- A contract for cooperation between modules enforced by the compiler
- no member variable
- Member functions cannot be implemented without declarations
Difference between interface and abstract class
- Abstract classes can have member variables
- Abstract classes can have partial implementations
- Abstract classes cannot have multiple inheritance, interfaces can
But why? (Why there are abstract classes and interfaces)
- From the user's point of view
- Emphasize contracts
- Force both parties to make mistakes
- The abstract class implements some public implementations, and the interface describes the functions of the class. Although the two are similar, they are not a dimensional concept.
inherit
- is - a relation
- The subclass adds or modifies (note that it cannot be reduced) the base class
package
inside the class | Inside the bag | Derived class | external | |
private | AND | N | N | N |
default | AND | AND | N | N |
protected | AND | AND | AND | N |
public | AND | AND | AND | AND |
- Also called package private by default
- Try to use only private and public
- Base class private -> subclass public ? Correct
- Base class public->subclass private? Error (common interview questions, subclasses cannot make base class permissions smaller)
Immutability
final keyword
- class declaration -> class cannot be inherited
- Function declaration function -> cannot be overridden in derived class
- Variable declaration variable -> can not point to other objects, the content can be changed
- static final variables -> used to define constant names are generally capitalized
Generics
- Is ArrayList<Integer> a List<Integer>? Yes
- Is List<Integer> a List<Object>? mistake
Convert List<Integer> to List<Object>
- new ArrayList<Object>(intList);正确
- (List<Object>)(List)intList;危险