Java BasicsJava 基础知识
The goal is not memorising terms. The goal is seeing Java code and knowing what each piece is called and why it exists.目标不是背术语,而是看到一段 Java 代码时,知道每一块东西该叫什么、它为什么存在。
Java source does not run directly as machine codeJava 代码不是直接变成机器码
You write .java files. javac compiles them into .class bytecode. The JVM runs that bytecode on each platform.你写的是 .java 文件,javac 把它编译成 .class bytecode,然后 JVM 在不同系统上运行这些 bytecode。
Hello.java→ javac →Hello.class→ JVM →run运行
- platform-independent: the same bytecode can run on JVMs for different platforms.:同一份 bytecode 可以交给不同平台的 JVM。
- memory management: objects are created with
newand later collected by the garbage collector.:对象用new创建,没引用后由 garbage collector 回收。 - secure: Java limits many unsafe operations through type checks, access control, and runtime checks.:类型检查、访问控制和运行时检查比 C 的直接内存操作更受限制。
The three common parts inside a class一段 Java class 里最常见的三块
class Circle {
private int x;
private int y;
private int r;
double area() {
return 3.14 * r * r;
}
}
class Circle: defines a type/template.:定义一个类型/模板。x,y,r: fields/attributes, the object's data.:field / attribute,也就是对象的数据。area(): a method, something the object can do.:method,也就是对象能做的事。
Practical memory hook: attribute = what it has; method = what it can do.实用记法:attribute = 它有什么;method = 它能干什么。
new creates the real objectnew 是真的创建对象
Circle c1 = new Circle();
Circle c2 = new Circle(2, 5, 10);
Circle is the class. new Circle(...) creates the object, also called an instance. A constructor initializes the object when it is born.Circle 是 class,new Circle(...) 创建出来的是 object,也叫 instance。constructor 是对象刚出生时负责初始化的特殊方法。
class Circle {
private int x, y, r;
Circle() {
this(1, 1, 1);
}
Circle(int x, int y, int r) {
this.x = x;
this.y = y;
this.r = r;
}
}
Access control protects object state访问控制是为了保护对象状态
Instead of letting outside code write c.r = -100, hide data and control updates through methods.不建议让外面直接 c.r = -100。更好的做法是把数据藏起来,再通过 method 检查。
class Circle {
private int r;
public void setRadius(int r) {
if (r <= 0) {
throw new IllegalArgumentException("radius must be positive");
}
this.r = r;
}
}
Practical Term Table实用术语表
| Code shape你看到的东西 | Name它叫什么 | Meaning怎么理解 |
|---|---|---|
class Student | class | A template/type, not a concrete object yet.模板/类型,还不是具体对象。 |
new Student() | instantiate | Create an instance/object.创建一个 instance/object。 |
String name | field / attribute | The object's data.对象的数据。 |
void study() | method | The object's behaviour.对象的行为。 |
this.name | this | The current object's own field.当前这个对象自己的 field。 |