Gyh's Braindump

Java Class

tag
Java
source
DT-On Java 8

Constructing

positioneaseboxintervaldue
front2.5036.002021-01-26T23:35:21Z

Default Constructor

When there are no constructor explicitly defined, the compiler will use a default constructor.

As long as a constructor is defined, no-arg constructor is provided by the compiler any more.

Default Values

When fields of a Class are Primitive Types, they have default values; when they are objects, they must be given an initial value, unless by using a Run Time Error (exception) will be thrown.

Local variables must be initialized. int x; // x will get some arbitrarty value, use before assigned a value will cause Compile Time Error

Constructors are actually static methods

Process of creating an object

positioneaseboxintervaldue
front2.5036.002021-01-26T23:38:09Z

Consider a class called Dog:

  1. (first time) creating an object, or access a static method, or static field of Dog, the Java interpreter locate Dog.class
  2. (first time) initialize static fields
  3. allocate enough storage for a Dog object on the heap and wipe it to zero
  4. setting primitive types to default values and references to null (even if fields are initialized manually)
  5. execute fields definition (instance initialization)
  6. execute constructors

this keyword

positioneaseboxintervaldue
front2.5036.002021-01-26T23:38:18Z
  • reference to current object
  • used to pass itself to another class’s methods
  • used to call other constructors inside a constructor
    • can only call one constructor
    • must be the first action in the constructor

Finalization

positioneaseboxintervaldue
front2.5036.002021-01-26T23:30:49Z

Java Garbage Collector first calls finalize() when it’s ready to release objects' storage, then on second pass of garbage-collection, it reclaim the objects' memory.

The need for finalize() is limited to special cases where objects can allocate storage in some way other than creating an object.

  • native methods: call non-Java code from Java

finalize() may not be called, so if a resource must be released, write another method and call it explicitly.

  • finalize() in this case can serve as a reminder/checker whether the release method has been called (prevent unknown memory leaks)