北邮果园 Java week1+week2 知识点【期中版】

PS:代码和讲解主要来自ChatGPT3.5和菜鸟教程
知识点按照官网上的知识清单总结,复习期中考试

请添加图片描述

请添加图片描述

Week1

Java syntax

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Primitive data types

  1. byte: Represents a signed 8-bit integer, with values ranging from -128 to 127.

  2. short: Represents a signed 16-bit integer, with values ranging from -32,768 to 32,767.

  3. int: Represents a signed 32-bit integer, with values ranging from -2^31 to 2^31-1.

  4. long: Represents a signed 64-bit integer, with values ranging from -2^63 to 2^63-1.

  5. float: Represents a single-precision 32-bit floating-point number.

  6. double: Represents a double-precision 64-bit floating-point number.

  7. char: Represents a single character or letter, using 16 bits of memory.

  8. boolean: Represents a true/false value, with only two possible values: true or false.

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

  1. while 循环

    while( 布尔表达式 ) {
      //循环内容
    }
    
  2. Java 增强 for 循环

    for(声明语句 : 表达式)
    {
       //代码句子
    }
    
     int [] numbers = {10, 20, 30, 40, 50};
     
      for(int x : numbers ){
         System.out.print( x );
         System.out.print(",");
      }
    
  3. 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 address
  • getClass(): 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

  • 7
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
实验1 类的定义、对象数组的使用 1. 定义一个学生类(Student), 属性有 1)非静态属性String studentNumber 2)非静态属性String studentName 3)非静态属性int markForMaths 4)非静态属性int markForEnglish 5)非静态属性int markForScience 方法有: 1)构造方法Student(String number, String name) 2)构造方法Student() 3)String getNumber() 4)String getName() 5)void enterMarks(int markForMaths, int markForEnglish, int markForScience) 6)int getMathsMark() 7)int getEnglishMark() 8)int getScienceMark() 9)double calculateAverage() 10)String toString() 返回学生信息,包括学号、姓名、数学成绩、英语成绩、科学成绩、平均成绩。 注意:为了保证calculateAverage返回double类型,需要把三个分数的和除以3.0,而不是3. 另外,分数的初始值是什么?如果每个分数初始值为0,会造成混淆,分数为0表示还没有输入分数,还是分数确实为0?有更好的初始值吗? 编写Student类,并且编写一个StudentTest类,对Student类进行测试。 StudentTest类运行效果如下: 请输入学生学号:2011211301 请输入学生姓名:王晓 请输入学生三门课成绩(数学,英语,科学):88,79,90 学生信息如下: 学号:2011211301 姓名:王晓 数学成绩:88 英语成绩:79 科学成绩:90 平均成绩:85.66666666666667 2.定义一个StudentList类用来存储Student对象 属性有 1)Student[] list; //list存储学生对象 2)int total; //学生总人数 方法有: 1)StudentList(int length) //length是数组长度 2)boolean add(Student stu) //增加stu到数组中,成功,返回true,否则false 3)boolean remove(int no) //删除第no个数组元素,删除成功,返回true,否则false 4)boolean remove(Student number) //删除学号为number的学生,删除成功,返回true,否则false 5)boolean isEmpty() //判断数组是否为空,若是,返回true,否则false 6)Student getItem(int no) //返回第no个学生 7)Student getItem(Student number) //返回学号为number的学生,若该生不存在,返回null。 8) int getTotal() 返回学生总人数 编写StudentList类,并且编写一个StudentListTest类,对StudentList类进行测试。 StudentListTest类运行效果: 菜单如下,请输入 1~8代表您要执行的操作: 1. 增加1个学生 2. 根据学号删除学生 3. 根据位置删除学生 4. 判断是否为空 5.根据位置返回学生 6.根据学号返回学生 7. 输出全部学生信息 8.退出程序 请输入您的操作:1 请输入学生信息: 学号:2011211301 姓名:王晓 数学成绩:88 英语成绩:79 科学成绩:90 ---目前有1个学生,信息为---: 学号:2011211301 姓名:王晓 数学成绩:88 英语成绩:79 科学成绩:90 平均成绩:85.66666666666667 请输入您的操作:1 学号:2011211311 姓名:李辉 数学成绩:80 英语成绩:79 科学成绩:93 ---目前有2个学生,信息为---: 学号:2011211301 姓名:王晓 数学成绩:88 英语成绩:79 科学成绩:90 平均成绩:85.66666666666667 姓名:李辉 数学成绩:80 英语成绩:79 科学成绩:93 平均成绩:84.0 请输入您的操作:5 请输入学生位置:10 对不起,没有对应的学生 请输入您的操作:5 请输入学生位置:2 学生信息如下: 姓名:李辉 数学成绩:80 英语成绩:79 科学成绩:93 平均成绩:84.0 请输入您的操作:3 请输入要删除第几个学生:2 删除成功 ---目前有1个学生,信息为:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赵鸣漩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值