Week1

History & Basic

image-20260308204608058

  1. edit
  2. compile
  3. Load+Verify
  4. Execute
  • Common Problems

    • file name=class name

    • compile:javac MyProgram.java

    • run:java MyProgram

    • Case sensitive

  • THREE Java comment formats:

    • // single line comment

    • /* many line comments, end with */

    • /** * comments here go * in a javadoc file */

  • Define a class,main method (excuted first)

image-20260308204636017

基础语法

  • Variables

image-20260308204653018

  • Basic data types

    • byte => short => int => long => float => double

    • long-L(不加为int),float-F(不加为double)

    • String不是原始数据类型,是objects

    image-20260308204721391

  • Naming Guidelines

    • 优先新词大写

    • Variables and methods→start with lowercase

    • Class names→start with uppercase

    • pronounceable, descriptive, brief

  • Reserved Words

image-20260308204733607

  • Operator Precedence

    • binary operators (except assignment) left to right;assignment operators are evaluated right to left

    image-20260308204747094

  • Control Structures

    • Selection: if, else, switch, Conditional Operator

      • switch

      image-20260308204800453

    • Repetition: for, while, do-while, break, continue

      • for

      image-20260308204810532

      • line marker

      image-20260308204820262

Introduction to OO

  • What is OO programming?

    Constructing software systems which are structured collections (or sets) of classes.

    These classes produce instances called objects, which communicate with each other using messages.

    object: a fundamental entity in Java.

  • object:

    • Attributes (or states) of an object: essentially anything that describes or quantifies an object

    • Operations (or behaviours) of an object: they mostly correspond to verbs in a requirements specification

  • class:

    • The class defines the attributes and operations exposed by one or more related objects

    • In Java, a class is to define a data type

    • Classes vs Objects: An object is an instance of a particular class,An object is defined by a class

  • Introducing Abstraction & Inheritance

    • Inheritance:superclass→subclasses,Overriding:redefined

    • Abstraction:Abstract out the common features

  • Object Basics: how OO works

    • 实战顺序:

      步骤 环节 动作
      1 声明类 public class ClassName (必须与文件名一致)
      2 定义属性 使用 private 定义 Instance Variables (状态)
      3 编写构造器 定义如何初始化对象 (无参/有参)
      4 封装接口 编写 getterssetters (控制访问权限)
      5 定义行为 编写其他业务逻辑 methods
      6 辅助方法 编写 toString() 方便打印调试
      7 测试验证 main 中用 new 创建对象,用 . 调用方法

核心蓝图:类与对象 (Class vs. Object)

  • class: description of a group of objects

    • ClassName: name of the class=file name

    • Class diagram notation: Class Name, Attributes, Methods=UML

    image-20260308204854999

  • object: a particular member of a class(or instance)

  • A class only exists at compile time; an object only exists at runtime.

第一层:内部结构(Variables & Methods)

  • A class provides the template for an object: attributes and operations

    • attributes are called instance variables
    • operations are called methods.

Variables

  • Attributes: state of an object=Instance variables+ Class variables(Static Variables)

  • Instance and Local Variables

    Variables Instance Local
    位置 inside a class but not inside a method 类中方法外 within a method 方法内
    初始化 initialised to the default value 自动赋默认值 NOT initialised to the default value must be initialised 必须手动初始化
    作用域 valid throughout the entire class 类的内部均可访问 have scope only within that method! 只在方法内

Methods

  • 声明:Methods’ syntax: modifier returnType methodName (parameters or parameter list)
    image-20260308204956118
    • 参数区别: 形参/实参

      • parameter:函数声明中, setPrice(int p)
      • argument:函数调用中, setPrice(10)
    • 签名 (Signature): name + parameters (types类型 and sequence顺序)

    • 重载 (Overloading): 方法允许重名,只要签名不同(参数列表)

    • Method parameters = local variables

      • They are declared inside the method.

      • They are valid (or in scope) only inside the method.

      • They are always initialised (by the caller of the method).

第二层:数据封装与访问控制

封装(Encapsulation)

  • 概念:Data Encapsulation(or information hiding) refers to when the internal state and operation are hidden from others.

    • 是什么:Objects are only accessible through well-defined interfaces

    • 为什么:An object should be self-governing

      We should NOT allow direct access to an object’s variables.

      Any changes to the object’s state (i.e. its variables) should be made ONLY by that object’s methods

    • 用什么:Access control allows for encapsulation!

  • 操作:Access Modifiers:We do not want to make all our instance variables and methods public

    • by qualifying variables with the public or private keywords

    image-20260308205031269

    • Each object has a public interface through which we can manipulate it(The only way)

    • The object’s state and internal operation are kept behind the scenes.

访问控制(Interface)

  • 概念:Accessor【getter】 and mutator【setter】 methods: If we want an attribute to be accessible outside the class→provide an interface to it

    • 意义:By using those methods, the object can control who sees and does what with it and thus has a better chance of remaining consistent.

    • 要求:always qualifying your instance variables and methods

  • Accessor methods: get, return= variableType getVariableName()

  • Mutator methods: set, this. =void setVariableName(VariableType)

    this. (调用者)的区分作用:this.name指向实例变量,name指向传入的形参。Sometimes, an object needs to be able to refer to itself – the keyword this is used to do that. In the setName method, name refers to the variable passed in and this.name refers to the cat’s instance variable name.

第三层:诞生与激活 (Constructors & Main)

Constructors

  • 特点:constructor: a special method, with same name as the class name, used for initialisation

    • name=class

    • It does not have a return type, not even void!

  • 无参构造器:默认参数为空 → 如果想先创建后改,无参构造器是必须的!image-20260308205102029

  • 有参构造器:此时调用需要加参数如果是有参,和mutator相似,要控制输入条件的话要同步或者更好的办法是reuse!!! image-20260308205215069

  • “signature”:不同构造器的灵活性:

    image-20260308205325109

Main

(2 uses) Test & Launch

  1. Tester: To “test” your real class.在这里用构造器
  2. Launcher: To launch (or start) your Java application.

第四层:执行与交互(Execution & Interaction)

  • Dot Notation:访问对象的公开成员(变量或方法)的路径=Using instance variables and methods

    • to access a (public) instance variable v of an object o, we reference it using the dot notation: o.v

    • to invoke a (public) method m of an object o, we also reference it using the dot notation: o.m()

  • **调用:**Calling(invoking) a method: store it in a variable or use it directly

    Program flow: Call stack→Pass-by-value(copy)

    image-20260308205346184

Arrays

数组的本质与定义 (What is an Array?)

  • 定义: data structure like maps, trees, sets;快速随机访问 provide fast random access by letting you use an index position to get any element in the array
  • 特性:
    • must be given a size
    • An array is an object
    • Array elements can be either primitives or objects(基本类型)或(引用类型)
  • 语法:两种(typeName arrayRef[]或typeName[] arrayRef),倾向于后者

实战操作:创建与初始化 (Creation & Initialization)

  • 创建对象数组:Declare+Create
1
2
3
Java int[ ] nums;//先声明
nums = new int[7];//后创建
Rabbit[] racers = new Rabbit[2];//或者一步到位
  • 给元素赋值:Give each element in the array a value

    • 如果存储的是对象,必须先 Construct(构造)每一个元素

    • 直接对未构造的元素用mutator会提示NullPointerException空指针异常

  • 访问属性:使用o.length获取长度

输出与显示 (Output & toString)

  • 默认行为:直接 print(nums) 会输出“类名@地址”。

  • 自定义输出:必须在类内重写 public String toString() 方法。

    逻辑链接:通过 Getter 接口(逻辑复用,方便修改)获取属性并拼接成字符串

1
2
3
4
5
6
public class Rabbit {
// all the stuff from Rabbit ... previous lectures
public String toString() {//注意是String数据类型下
return this.getName() + " is a " + this.getFurType() +" Rabbit that runs at " + this.getSpeed() + " km/hr.";
}//类外直接用get接口可以省个print(this)
}

拷贝与传递 (Copying & Passing)

  • 引用拷贝 (Reference Copying):arrayA = arrayB

  • **数据拷贝 (Data Copying):**THREE ways

    1. Use a loop to copy all individual elements.
1
2
3
4
int[] nums2=new int[nums.length]; 
for(int i=0;i<nums.length;i++){
nums2[i]=nums[i];
}
  1. Use the static arraycopy method in the System class.
  • Modifier and Type: static void

  • System.arraycopy(src, srcPos, dest, destPos, length) →→(目标数组)dest=src(源数组), Pos要是都从头就是0

  1. Use the clone method to copy arrays. (Out of scope)
  • 作为参数传递(Passing Arrays to Methods):passes a copy of the reference variable to the array object,传递的那个“值”不是数据本身,而是引用的副本(a copy of the reference)=两张写着相同地址的纸条image-20260308205416088

    image.png image-20260308205615359

    补充:Javadocs

    1. 作用与生成

  • 作用:自动生成 HTML 格式的“代码维护手册”。

    Run the javadoc tool over the source code, to parse the declarations and Doc comments, generating a set of HTML pages.

  • 生成命令javadoc -d docs FileName.java-d docs 指定输出目录)。

    2. 文档注释格式 (Doc Comments)

  • 使用 /** ... */ 格式,由描述部分标签部分组成:

    General form of Doc comments:A Doc comment is made up of two parts: a description, followed by zero or more tags, with a blank line (containing a single asterisk (*)) between these two sections.

    /**
    * This is the description part of a Doc comment.
    *
    * @tag Comment for the tag
    */
    
    * @author (classes and interfaces only, required)
    * @version (classes and interfaces only, required)
    *
    * @param (methods and constructors only)
    * @return (methods only)
    * @exception
    * @see
    * @since
    * @serial (or @serialField or @serialData)
    * @deprecated