mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4
550 words
3 minutes
Core Java Study Day 02
2022-07-14

Java study & review; this article mainly references Java Core Technologies Volume as the learning reference.

Chapter 4: Objects and Classes#

1. Class#

Object-Oriented Programming (OOP)

Class: encapsulates instance fields + methods

Class >== Inheritance (is-a)/ Dependency (uses-a)/ Aggregation (has-a) ==> Class

DVjasvCERhIqiUH.png

2. Built-in Classes#

// Math
// Date
Date date = null; //类似于cpp的对象指针
date = new Date();
System.out.println(date.toString());

LocalDate#

// LocalDate
System.out.println(LocalDate.now());
LocalDate date = LocalDate.now(); //construct current date
date = LocalDate.of("year","month","day"); //construct specified date
int today = date.getDayOfMonth();
int getYear();
int getMonthValue();
int getDayofMonth();
int getDayofWeek(); //1~7
// n days earlier, n days later
date = date.minusDays(n);
date = date.plusDays(n);
// is leap year
date.isLeapYear();
// number of days in the current year and in the current month
date.lengthOfYear();
date.lengthOfMonth();
  • Use LocalDate to print the current month’s calendar
public class chapter04main {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
int month = date.getMonthValue();
int today = date.getDayOfMonth();
date = date.minusDays(today-1); // first day of the month
DayOfWeek week = date.getDayOfWeek();
System.out.println("Mon Tue Wed Thu Fri Sat Sun");
for(int i=0;i<week.getValue();i++) System.out.printf(" ");
while (date.getMonthValue() == month){
int now = date.getDayOfMonth();
System.out.printf("%3d",now); // print date
if(now == today) System.out.printf("*");
else System.out.printf(" ");
date = date.plusDays(1); // next day
if(date.getDayOfWeek().getValue() == 1) System.out.println();
}
}
}

KiyBMQgl85CdVjU.png

3. Custom Classes#

class Test{
//field
private int t;
//constructor
public Test(/*...*/){
//...
}
// method
public void test(int n){
System.out.println("just test");
}
}
  • Run multiple source files
javac Test*.java
  • Instantiation
// Using the constructor
Test test1 = new Test();
var test2 = new Test();
// detect null
t = Objects.requireNonNullElse(n,"unknown"); //warn but accept
Objects.requireNonNull(n,"not to be null"); //reject directly
  • Explicit parameter, implicit parameter

In test1.test(3), test1 is the implicit parameter, and 3 is the explicit parameter.

  • Encapsulation

Do not return private objects of the class

  • Access modifiers

public: public

private: private

  • final

Must be initialized, and the reference cannot be changed to point to another object, though the object it points to can be modified.

private final StringBuilder eva;
eva = new StringBuilder(); //must be initialized
eva.append("ok!\\n"); //legal

4. Static Methods and Static Fields#

static int number = 1; //static field, shared by the class
static final double PI = 3.141592653589; //static constant
  • Static methods

static int getNum(){...}

There are no implicit instances; call directly on the class. e.g. Test.getNum()

No object state required; just access the class’s static fields

  • Factory methods

Similar to the constructors of LocalDate and NumberFormat.

  • main

The main method is also a static method.

5. Method Parameters#

  • Call by value (Java default)
  • Call by reference
  • Call by name (used by Algol)

Call by value: parameters are copies (primitive data types).

Object references allow the parameter to refer to the object, but it is still passed by value. e.g., you cannot swap two objects.

6. Object Construction#

  • Overloading

Same name, different parameter lists (not including return type)

  • No-arg constructor

Initialize to default values.

P.S. When there is custom construction, you must provide a no-arg constructor yourself.

  • Explicit field initialization

private String name = ""; initialize directly in the class.

  • Using this to delegate to another constructor
public Test(double s){
this("Test "+Double.toString(s));
}
  • Initialization blocks
class Test{
private static int Aid = 1;
private int id;
// initialization block
// static, if present, runs when the class is loaded for the first time.
{
id = Aid;
Aid ++;
}
//...
}

As long as you construct an object, the initialization block will run. It runs before the constructor.

  • Destruction

Java can perform automatic garbage collection

7. Packages#

package

  • Package name
  • Importing classes

Directly use all classes within the package.

Use public classes from other packages.

Fully qualified name

java.time.LocalDate today = java.time.LocalDate.now();

  • import

import java.time.*; | import java.time.LocalDate;

You can only use * to import a package,

  • Static imports

import static java.lang.System.*;

You can directly use out.println();

  • Packages

package cc.dreaife.chapter04;

If there is no package statement, the classes in the file belong to the unnamed package.

  • Package access

If neither public nor private is specified, it can be accessed within the same package.

  • Class path

Classes can be stored in JAR files, which can contain multiple class files and subdirectories.

JARs organize files and subdirectories using ZIP format.

# Set the classpath
java -classpath ${PATH(JAR)} ${className};
export CLASSPATH=${PATH};
set CLASSPATH=${PATH}

8. JAR Files#

  • Creating a jar file

jar cvf jarFileName file1 file2 ...

  • Manifest file

META-INF/MANIFEST.MF

jar cfm jarName manifestName ...

  • Executable jar file

java -jar jarName

  • Multi-version jar files

9. Documentation Comments#

javadoc => HTML files

  • Comment placement

Public classes and interfaces at the module/package level, public or protected fields, public or protected constructors and methods

/**...*/ comments

@ param tag + free-form text (the first sentence should be a brief summary; HTML modifiers may be used)

  • Class comments

After imports, before the class definition

  • Method comments

@param

Parameter description, can span multiple lines, HTML modifiers may be used

  • @return

Return value, can span multiple lines, HTML modifiers may be used

  • @throws

Thrown exceptions

/**
* testA
* @param s
* @param num
* @return string
*/
public String testA(String s,int num){
return s + Integer.toString(num);
}
  • Field comments
  • General notes

@author name@since text@version text@see | @link (use hyperlinks to packages, classes, and methods)

  • Package comments

Add a separate file within the package directory.

package-info.javapackage.html extract the text between …

  • Comment extraction
javadoc -encoding UTF-8 -d ../doc Chapter04 #extract package
javadoc -encoding UTF-8 -d docTest test.java #extract class

10. Class Design Tips#

  • Ensure data is private
  • Data initialization
  • Don’t use too many primitive types
  • Not everything needs get() and set()
  • Avoid classes with too many responsibilities
  • Class names and method names should reflect their responsibilities
  • Prefer immutable classes
Share

If this article helped you, please share it with others!

Core Java Study Day 02
https://dreaife.tokyo/en/posts/java-core-tech-day02/
Author
dreaife
Published at
2022-07-14
License
CC BY-NC-SA 4.0

Some information may be outdated

Related Posts Smart
1
Core Java Study Day 01
cs-base This article mainly introduces core Java topics including an overview of Java, environment setup, basic program structure, data types, variables, operators, string processing, input and output, flow control, and array usage. It emphasizes Java simplicity, object-oriented features, and cross-platform capabilities, and also lists key terms such as JDK and JRE with detailed explanations.
2
Java IO
cs-base Java IO covers the basic concepts of input and output streams, including the classification of byte streams and character streams and their common classes such as InputStream, OutputStream, Reader, and Writer. Byte streams are used for raw byte data, while character streams are used for character data. Buffered streams improve performance by reducing the number of IO operations. Adapter and decorator patterns are widely used in Java IO streams to enhance functionality and coordinate different interfaces. Java IO models include synchronous blocking IO, non-blocking IO, and asynchronous IO, each suited to different scenarios.
3
Java Concurrent Programming
cs-base This article introduces the basics of Java concurrent programming, including the definitions of threads and processes, Java thread implementation mechanisms, thread life cycle, the differences between concurrency and parallelism, the concepts of synchronous and asynchronous execution, and the advantages and disadvantages of multithreading. It also discusses thread safety, deadlocks and how to avoid them, the use of the volatile keyword, the difference between optimistic and pessimistic locking, and how to use thread pools and Future to improve execution efficiency. Finally, it introduces the application scenarios and principles of tools such as CyclicBarrier and CountDownLatch.
4
Java NIO
cs-base NIO (New I/O) is the non-blocking I/O model introduced in Java 1.4 to solve performance bottlenecks of traditional BIO. Its core components include Buffer, Channel, and Selector, allowing a small number of threads to handle multiple connections. NIO also supports zero-copy techniques to improve I/O efficiency, and NIO-based frameworks such as Netty are recommended to simplify network programming.
5
Java AQS
cs-base AQS (AbstractQueuedSynchronizer) is an abstract class in Java mainly used to build locks and synchronizers. Its core principle relies on a CLH-style queue to implement thread blocking, waiting, and wake-up mechanisms. AQS supports both exclusive and shared resource access modes. Common synchronization utilities include Semaphore and CountDownLatch, which are used to control the number of threads accessing resources and to wait for multiple threads to finish tasks. CyclicBarrier allows a group of threads to block at a synchronization point until the last thread arrives.

Table of Contents