PS:代码和讲解主要来自ChatGPT3.5和菜鸟教程
知识点按照官网上的知识清单总结,复习期中考试
文章目录
Week1
Java syntax
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Primitive data types
-
byte
: Represents a signed 8-bit integer, with values ranging from -128 to 127. -
short
: Represents a signed 16-bit integer, with values ranging from -32,768 to 32,767. -
int
: Represents a signed 32-bit integer, with values ranging from -2^31 to 2^31-1. -
long
: Represents a signed 64-bit integer, with values ranging from -2^63 to 2^63-1. -
float
: Represents a single-precision 32-bit floating-point number. -
double
: Represents a double-precision 64-bit floating-point number. -
char
: Represents a single character or letter, using 16 bits of memory. -
boolean
: Represents a true/false value, with only two possible values:true
orfalse
.
byte b = 10;
short s = 100;
int i = 1000;
long l = 1000000L; // note the "L" suffix to indicate a long value
float f = 3.14f; // note the "f" suffix to indicate a float value
double d = 3.14159;
char c = 'A';
boolean bool = true;
Assignment 赋值
int x = 10;
Variables 变量
略
Control structures
-
while 循环
while( 布尔表达式 ) { //循环内容 }
-
Java 增强 for 循环
for(声明语句 : 表达式) { //代码句子 } int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ){ System.out.print( x ); System.out.print(","); }
-
switch case
switch(expression){ case value : //语句 break; //可选 case value : //语句 break; //可选 //你可以有任意数量的case语句 default : //可选 //语句 }
Keywords
略
Plagiarism
啥玩意啊这词
OO
Classes and Object ; Instance variables ; method ; Constructors
public class Car { // Classes
private String make; //Instance variables
private String model;
private int year;
public Car(String make, String model, int year) { //Constructors
this.make = make;
this.model = model;
this.year = year;
}
public void start() { //method
System.out.println("Starting the " + year + " " + make + " " + model);
}
public static void main(String[] args) {
Car myCar = new Car("Toyota", "Camry", 2021); //Object
myCar.start();
}
}
Data Hiding/Access Modifiers
public class EncapTest{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
public String getName(){
return name;
}
public String getIdNum(){
return idNum;
}
public void setAge( int newAge){
age = newAge;
}
public void setName(String newName){
name = newName;
}
public void setIdNum( String newId){
idNum = newId;
}
}
Week 2
Arrays
declaring/initializing
double[] myList = new double[size];
copying/printing
用循环copy和print都可以
int[] originalArray = {1, 2, 3, 4, 5};
int[] copiedArray = new int[originalArray.length];
for (int i = 0; i < originalArray.length; i++) {
copiedArray[i] = originalArray[i];
}
copy的方法
//1
int[] originalArray = {1, 2, 3, 4, 5};
int[] copiedArray = new int[originalArray.length];
System.arraycopy(originalArray, 0, copiedArray, 0, originalArray.length);
//2
int[] originalArray = {1, 2, 3, 4, 5};
int[] copiedArray = Arrays.copyOf(originalArray, originalArray.length);
print的方法
int[] arr = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(arr));
using methods with arrays
//自己创建的方法
public class Example {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
printArray(arr);
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
Writing Java programs
ArrayLists 动态数组
import java.util.ArrayList; //用之前要引入
ArrayList<String> myList = new ArrayList<String>(); //创建
myList.add("element1"); //Add elements to the ArrayList
String element = myList.get(0);//Access elements in the ArrayList
myList.remove(0); //Remove elements from the ArrayList
int size = myList.size(); //Get the size of the ArrayList
方法 | 描述 |
---|---|
add() | 将元素插入到指定位置的 arraylist 中 |
addAll() | 添加集合中的所有元素到 arraylist 中 |
clear() | 删除 arraylist 中的所有元素 |
clone() | 复制一份 arraylist |
contains() | 判断元素是否在 arraylist |
get() | 通过索引值获取 arraylist 中的元素 |
indexOf() | 返回 arraylist 中元素的索引值 |
removeAll() | 删除存在于指定集合中的 arraylist 里的所有元素 |
remove() | 删除 arraylist 里的单个元素 |
size() | 返回 arraylist 里元素数量 |
isEmpty() | 判断 arraylist 是否为空 |
subList() | 截取部分 arraylist 的元素 |
set() | 替换 arraylist 中指定索引的元素 |
sort() | 对 arraylist 元素进行排序 |
toArray() | 将 arraylist 转换为数组 |
toString() | 将 arraylist 转换为字符串 |
ensureCapacity() | 设置指定容量大小的 arraylist |
lastIndexOf() | 返回指定元素在 arraylist 中最后一次出现的位置 |
retainAll() | 保留 arraylist 中在指定集合中也存在的那些元素 |
containsAll() | 查看 arraylist 是否包含指定集合中的所有元素 |
trimToSize() | 将 arraylist 中的容量调整为数组中的元素个数 |
removeRange() | 删除 arraylist 中指定索引之间存在的元素 |
replaceAll() | 将给定的操作内容替换掉数组中每一个元素 |
removeIf() | 删除所有满足特定条件的 arraylist 元素 |
forEach() | 遍历 arraylist 中每一个元素并执行特定操作 |
Java API
这里的API应该不是接口的意思,而是 (Application Programming Interface) 的简称,讲的就是用命令行javac和java去运行java文件的过程。
Inheritance
extends(is-a)
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // inherited from Animal class
dog.bark();
}
}
aggregation (has-a) 一个类里用了其他类当成员变量
class Address {
String city;
String state;
Address(String city, String state) {
this.city = city;
this.state = state;
}
}
class Person {
String name;
Address address;
Person(String name, Address address) {
this.name = name;
this.address = address;
}
}
public class Main {
public static void main(String[] args) {
Address address = new Address("New York", "NY");
Person person = new Person("John", address);
System.out.println(person.name + " lives in " + person.address.city + ", " + person.address.state);
}
}
//In this example, the Person class has an aggregation relationship with the Address class. The Person class has an instance variable of Address type, which represents the person's address.
superclass and subclass
class Animal { //superclass
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal { //subclass
void bark() {
System.out.println("Barking...");
}
}
access modifiers
Java has four types of access modifiers:
1.Public
:Members declared as public can be accessed from any class, in any package.
2.Protected
:Members declared as protected can be accessed from the same class, any subclass in the same package, or any subclass in a different package.
3.Default
(package-private):Members declared without any access modifier are accessible within the same package only.
4.Private
:Members declared as private can be accessed only within the same class.
Here’s an example:
public class Animal {
public String name;
protected int age;
double weight; // default
private boolean isAlive;
public Animal(String name, int age, double weight, boolean isAlive) {
this.name = name;
this.age = age;
this.weight = weight;
this.isAlive = isAlive;
}
public void eat() {
System.out.println("Animal is eating...");
}
protected void sleep() {
System.out.println("Animal is sleeping...");
}
void move() { // default
System.out.println("Animal is moving...");
}
private void die() {
this.isAlive = false;
System.out.println("Animal has died...");
}
}
public class Dog extends Animal {
public Dog(String name, int age, double weight, boolean isAlive) {
super(name, age, weight, isAlive);
}
public void bark() {
System.out.println("Dog is barking...");
}
public void displayAge() {
System.out.println("Dog's age is: " + this.age);
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy", 3, 10.5, true);
System.out.println("Dog's name is: " + dog.name);
System.out.println("Dog's weight is: " + dog.weight);
dog.eat();
dog.sleep();
dog.move();
dog.bark();
dog.displayAge();
}
}
In this example, the Animal class has members declared with different access modifiers. The Dog class extends the Animal class and can access the superclass’s public and protected members. The Dog class can also access the superclass’s default member since it belongs to the same package. However, it cannot access the superclass’s private member directly.
polymorphism 多态
多态存在的三个必要条件:
- 继承 extends
- 重写 Method overriding
- 父类引用指向子类对象:
Parent p = new Child();
Animal p = new Dogs();
当使用多态方式调用方法时,首先检查父类中是否有该方法,如果没有,则编译错误;如果有,再去调用子类的同名方法。
面向对象进阶-09-认识多态 强烈建议看视频了解下多态的用处在哪
面向对象进阶-10-多态中调用成员的特点 9分钟之后这个内存图真的很有用,狠狠地看
调用成员变量:编译看左边,运行也看左边
调用成员方法:编译看左边,运行看右边(子类有,就用子类)
public class Test {
public static void main(String[] args) {
show(new Cat()); // 以 Cat 对象调用 show 方法
show(new Dog()); // 以 Dog 对象调用 show 方法
Animal a = new Cat(); // 向上转型
a.eat(); // 调用的是 Cat 的 eat
Cat c = (Cat)a; // 向下转型
c.work(); // 调用的是 Cat 的 work
}
public static void show(Animal a) {
a.eat();
// 类型判断 强制转换**为了能使用子类特有的方法** 这也是多态的一个缺点
if (a instanceof Cat) { // 猫做的事情
Cat c = (Cat)a;
c.work();
} else if (a instanceof Dog) { // 狗做的事情
Dog c = (Dog)a;
c.work();
}
//以上强制转换可以简写为
if(a instanceof Cat c) {
c.work();
}else if (a instanceof Dog c) { // 狗做的事情
c.work();
}
}
}
abstract class Animal {
abstract void eat();
}
class Cat extends Animal {
public void eat() {
System.out.println("吃鱼");
}
public void work() {
System.out.println("抓老鼠");
}
}
class Dog extends Animal {
public void eat() {
System.out.println("吃骨头");
}
public void work() {
System.out.println("看家");
}
}
Method overriding: 重写
class Animal {
public void makeSound() {
System.out.println("Animal is making a sound...");
}
}
class Dog extends Animal {
//Override
public void makeSound() {
System.out.println("Dog is barking...");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
Dog dog = new Dog();
animal.makeSound(); // Output: Animal is making a sound...
dog.makeSound(); // Output: Dog is barking...
Animal animal1 = new Dog(); // Polymorphism
animal1.makeSound(); // Output: Dog is barking...
}
}
Method overloading:
Method overloading is a mechanism where a class can have multiple methods with the same name but different parameter lists. The methods must have different parameter types or a different number of parameters. When a method is called, the JVM determines which method to call based on the arguments passed to the method.
class Calculator {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
int sum1 = calculator.add(1, 2);
System.out.println("Sum1: " + sum1); // Output: Sum1: 3
double sum2 = calculator.add(2.5, 3.5);
System.out.println("Sum2: " + sum2); // Output: Sum2: 6.0
}
}
Abstract classes 抽象类
抽象类除了不能实例化对象之外,类的其它功能依然存在,成员变量、成员方法和构造方法的访问方式和普通类一样。
由于抽象类不能实例化对象,所以抽象类必须被继承,才能被使用。
public abstract class Animal {
public abstract void makeSound();
public void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
Animal animal = new Animal(); // This will result in a compilation error
Animal animal = new Dog(); // This is valid
Abstract methods
如果你想设计这样一个类,该类包含一个特别的成员方法,该方法的具体实现由它的子类确定,那么你可以在父类中声明该方法为抽象方法。
Abstract 关键字同样可以用来声明抽象方法,抽象方法只包含一个方法名,而没有方法体。
抽象方法没有定义,方法名后面直接跟一个分号,而不是花括号。
public abstract class Employee
{
private String name;
private String address;
private int number;
public abstract double computePay();
//其余代码
}
- 如果一个类包含抽象方法,那么该类必须是抽象类。
- 任何子类必须重写父类的抽象方法,或者声明自身为抽象类。
Object classes
Object类是一切类的父类
The Object
class provides some basic methods that are available to all objects in Java. Some of the most commonly used methods of the Object
class are:
toString()
: This method returns a string representation of the object.equals(Object obj)
: This method compares the current object with the specified object for equality.hashCode()
: This method returns the hash code value of the object. The hash code value is an integer that represents the object’s memory addressgetClass()
: This method returns the class of the object.wait()
: This method causes the current thread to wait until another thread notifies it.notify()
: This method wakes up a single thread that is waiting on the object’s monitor.notifyAll()
: This method wakes up all threads that are waiting on the object’s monitor.
Here is an example of a class that overrides the toString()
and equals()
methods of the Object
class:
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Name: " + name + ", Age: " + age;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Person) {
Person other = (Person) obj;
return this.name.equals(other.name) && this.age == other.age;
}
return false;
}
}
super()
super关键字:我们可以通过super关键字来实现对父类成员的访问,用来引用当前对象的父类。
class Animal {
String name;
public Animal(String name) {
this.name = name;
}
public void makeSound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
public Dog(String name) {
super(name); // calling parent class constructor
}
@Override
public void makeSound() {
super.makeSound(); // calling parent class method 1. 用方法
System.out.println("Dog sound");
}
}
class Animal {
String name;
public Animal(String name) {
this.name = name;
}
}
class Dog extends Animal {
int age;
public Dog(String name, int age) {
super(name); // calling parent class constructor 2. 用来初始化
this.age = age;
}
}
END