Introduction to Java (3): Object-oriented, String, and Collections

1. Object-oriented definition class


1. Create a Car

package com.wielun;

public class Car {
    // 属性(成员变量)
    String name;
    double price;

    // 行为
    public void start() {
        System.out.println(name + ",价格是: " + price + " start...");
    }

    public void run() {
        System.out.println(name + ",价格是: " + price + " run...");
    }
}

2. Create a Test

package com.wielun;

public class Test {
    public static void main(String[] args) {
        // 类名 对象名 = new 类名();
        Car c = new Car();
        c.name = "领克03";
        c.price = 17.5;
        c.start();
        c.run();
    }
}

result:

领克03,价格是: 17.5 start...
领克03,价格是: 17.5 run...

2. Object-oriented syntax


1. Constructor

Parameterized constructor (default exists): When initializing an object, the data of member variables adopt default values.
Parameterized constructor: When initializing an object, you can assign values ​​to the object at the same time
. Any class defined will come with none by default. The parameter constructor is written or not.
Once the parameterized constructor is defined, the parameterless constructor is gone. At this time, you need to write a parameterless constructor yourself.

(1) Create a Car
package com.wielun;

public class Car {
    String name;
    double price;

    public Car() {
        System.out.println("无参数构造器...");
    }

    public Car(String n, double p) {
        System.out.println(n + ",价格是: " + p + " 有参数构造器...");
    }
}
(2) Create a Test
package com.wielun;

public class Test {
    public static void main(String[] args) {
        // 类名 对象名 = new 类名();
        Car c = new Car();
        System.out.println(c.name);
        System.out.println(c.price);

        Car c2 = new Car("领克03", 17.5);
        System.out.println(c.name);
        System.out.println(c.price);
    }
}

result:

无参数构造器...
null
0.0
领克03,价格是: 17.5 有参数构造器...
null
0.0

2. this keyword

Function: Appears in member methods and constructors to represent the address of the current object, used to access member variables and member methods of the current object

(1) Create a Car
package com.wielun;

public class Car {
    String name;
    double price;

    public Car(String name, double price) {
        this.name = name;
        this.price = price;
    }
}
(2) Create a Test
package com.wielun;

public class Test {
    public static void main(String[] args) {
        // 类名 对象名 = new 类名();
        Car c = new Car("领克03", 17.5);
        System.out.println(c.name);
        System.out.println(c.price);
    }
}

result:

领克03
17.5

3. Three major characteristics of object-oriented


1. Packaging

Generally, member variables are hidden using the private (private) keyword modification. After private modification, the member variables can only be accessed in the current class through the public
getter and setter methods that provide public modification, exposing their value and assignment
encapsulation benefits:

  • Enhanced program code security
  • Proper encapsulation can improve development efficiency and make the program easier to understand and maintain.
(1) Create a Student
package com.wielun.encapsulation;

public class Student {
    private int age;
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age >= 0 && age <= 200) {
            this.age = age;
        } else {
            System.out.println("年龄不合法");
        }
    }
}
(2) Create a Test
package com.wielun.encapsulation;

public class Test {
    public static void main(String[] args) {
        Student s = new Student();
        s.setAge(-20);
        System.out.println(s.getAge());
    }
}

result:

年龄不合法
0

2、JavaBean

It can be understood as an entity class, and its objects can be used to encapsulate data member variables in the program.
Use private modification
to provide setXxx()/getXxx() corresponding to each member variable.

(1) Create a User
package com.wielun.javabean;

public class User {
    // 1.成员变量私有
    private String name;
    private double height;
    private double salary;

    // 3.必须有无参数构造器(默认)

    public User() {
    }

    // 4.有参数构造器(不是必须,可以选择)

    public User(String name, double height, double salary) {
        this.name = name;
        this.height = height;
        this.salary = salary;
    }

    // 2.必须提供成套的getter和setter方法暴露成员变量的取值和赋值
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}
(2) Create a Test
package com.wielun.javabean;

public class Test {
    public static void main(String[] args) {
        // 1.调用无参数构造器创建对象
        User u = new User();
        u.setName("wielun");
        u.setHeight(175.0);
        u.setSalary(100);
        System.out.println(u.getName());
        System.out.println(u.getHeight());
        System.out.println(u.getSalary());

        // 2.调用有参数构造器创建对象
        User u2 = new User("wielun1",170.0,1000);
        System.out.println(u2.getName());
        System.out.println(u2.getHeight());
        System.out.println(u2.getSalary());
    }
}

result:

wielun
175.0
100.0
wielun1
170.0
1000.0

4. String


API下载地址:https://www.oracle.com/java/technologies/downloads/

1 Overview

  • The java.lang.String class represents a string. Variables defined by the String class can be used to point to string objects and then operate on the string.

  • All string literals in Java programs (e.g. "wielun") are objects of this class

  • String is often called an immutable string type because its object cannot be changed after it is created.

2. First experience

package com.wielun.string;

public class StringDemo1 {
    public static void main(String[] args) {
        String name = "wielun";
        name += "123";
        System.out.println(name);
    }
}

result:

wielun123

3. Login case

package com.wielun.string;

import java.util.Scanner;

public class StringDemo2 {
    public static void main(String[] args) {
        String okLoginName = "admin";
        String okPassword = "123456";

        Scanner sc = new Scanner(System.in);
        for (int i = 1;i <= 3; i++) {
            System.out.println("name: ");
            String loginName = sc.next();

            System.out.println("password: ");
            String password = sc.next();

            if (okLoginName.equals(loginName)) {
                if (okPassword.equals(password)) {
                    System.out.println("login successful!!!");
                    break;
                } else {
                    System.out.println("password error!!!");
                }
            } else {
                System.out.println("login name error!!!");
            }
        };

    }
}

4. Private number case

package com.wielun.string;

import java.util.Scanner;

public class StringDemo3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("phone: ");
        String tel = sc.next();

        String before = tel.substring(0, 3);
        String after = tel.substring(7);

        String s = before + "****" + after;
        System.out.println(s);
    }
}

5. Collection ArrayList


1 Introduction

  • A collection is similar to an array and is also a container used to hold data.

  • The size of the collection is not fixed and can be changed dynamically after startup, and the type can also be chosen to be unfixed.

  • Sets are very suitable for business scenarios where the number of elements is uncertain and addition and deletion operations are required.

2. First experience

package com.wielun.arraylist;

import java.util.ArrayList;

public class ArrayListDemo1 {
    public static void main(String[] args) {
        // 1.创建ArrayList集合对象
        ArrayList list = new ArrayList();

        // 2.添加数据
        list.add("Java");
        list.add("Golang");
        list.add("Python");
        System.out.println(list);

        // 3.给指定索引位置插入元素
        list.add(1,"wielun");
        System.out.println(list);
    }
}

result:

[Java, Golang, Python]
[Java, wielun, Golang, Python]

3. First experience with generics

ArrayList: It is actually a generic class that can constrain the collection object to only operate on certain data types during the compilation phase.

package com.wielun.arraylist;

import java.util.ArrayList;

public class ArrayListDemo2 {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
//        list.add(23);      //会报错
        System.out.println(list);

        ArrayList<Integer> list2 = new ArrayList<>();
        list2.add(23);
        list2.add(21);
        System.out.println(list2);
    }
}

result:

[Java, Python]
[23, 21]

4. Commonly used methods of generics

package com.wielun.arraylist;

import java.util.ArrayList;

public class ArrayListDemo3 {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("Golang");
        list.add("Golang");
        list.add("MySQL");

        // 1.public E get(int index): 获取某个索引位置处的元素值
        String e = list.get(1);
        System.out.println(e);

        // 2.public int size(): 获取集合的大小(元素个数)
        System.out.println(list.size());

        // 3.完成集合的遍历
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }

        // 4.public E remove(int index): 删除某个索引位置处的元素值,并返回删除的元素值
        System.out.println(list);
        String e2 = list.remove(1);
        System.out.println(e2);
        System.out.println(list);

        // 5.public boolean remove(Object o): 直接删除元素值,删除成功返回true,删除失败返回false
        System.out.println(list.remove("Golang"));  // 只会删除第一个元素
        System.out.println(list);

        // 6.public E set(int index,E element): 修改某个索引位置处的元素值
        list.set(0, "wielun");
        System.out.println(list);
    }
}

result:

Python
5
Java
Python
Golang
Golang
MySQL
[Java, Python, Golang, Golang, MySQL]
Python
[Java, Golang, Golang, MySQL]
true
[Java, Golang, MySQL]
[wielun, Golang, MySQL]

5. Movie cases

package com.wielun.arraylist;

import java.util.ArrayList;

public class ArrayListTest5 {
    public static void main(String[] args) {
        // 1.定义一个电影类: Movie
        // 2.定义一个ArrayList集合存储这些影片对象
        ArrayList<Movie> movies = new ArrayList<>();
        // 3.创建影片对象封装电影数据,把对象加入到集合中去
//        Movie m1 = new Movie("<<肖生克的救赎>>", 9.7, "罗宾斯");
//        movies.add(m1);
        movies.add(new Movie("《肖生克的救赎》", 9.7, "罗宾斯"));
        movies.add(new Movie("《爱情神话》", 8.1, "徐峥"));
        movies.add(new Movie("《玉面情魔》", 6.7, "布莱德利·库珀"));
        // 4.遍历集合中的影片对象并展示出来
        for (int i = 0; i < movies.size(); i++) {
            Movie movie = movies.get(i);
            System.out.println("片名: " + movie.getName());
            System.out.println("评分: " + movie.getScore());
            System.out.println("主演: " + movie.getActor());
        }
    }
}

Movies:

package com.wielun.arraylist;

public class Movie {
    private String name;
    private double score;
    private String actor;

    public Movie() {
    }

    public Movie(String name, double score, String actor) {
        this.name = name;
        this.score = score;
        this.actor = actor;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    public String getActor() {
        return actor;
    }

    public void setActor(String actor) {
        this.actor = actor;
    }
}

result:

片名: 《肖生克的救赎》
评分: 9.7
主演: 罗宾斯
片名: 《爱情神话》
评分: 8.1
主演: 徐峥
片名: 《玉面情魔》
评分: 6.7
主演: 布莱德利·库珀

6. Student search case

package com.wielun.arraylist;

import java.util.ArrayList;
import java.util.Scanner;

public class ArrayListTest6 {
    public static void main(String[] args) {
        // 1.定义一个学生类,后期用于创建对象封装学生数据
        // 2.定义一个集合对象用于装学生对象
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student("20220221","wielun1",24,"Java一班"));
        students.add(new Student("20220222","wielun2",25,"Python一班"));
        students.add(new Student("20220223","wielun3",26,"Golang一班"));
        students.add(new Student("20220224","wielun4",27,"运维一班"));

        // 3.遍历集合中的学生对象并展示数据
        for (int i = 0; i < students.size(); i++) {
            Student s = students.get(i);
            System.out.println(s.getStudyId() + "\t" + s.getName() + "\t" + s.getAge() + "\t" + s.getClassName());
        }

        // 4.让用户不断的输入学号,可以搜索出改学生对象并展示出来
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("student num: ");
            String id = sc.next();
            Student s= getStudentByStudyId(students, id);

            if (s == null) {
                System.out.println("无此人");
            } else {
                System.out.println(s.getStudyId() + "\t" + s.getName() + "\t" + s.getAge() + "\t" + s.getClassName());
            }
        }
    }

    /**
     根据学号找出学生对象
     * @param students
     * @param studyId
     * @return
     */
    public static Student getStudentByStudyId(ArrayList<Student> students, String studyId) {
        for (int i = 0; i < students.size(); i++) {
            Student s = students.get(i);
            if (s.getStudyId().equals(studyId)) {
                return s;
            }
        }
        return null;
    }
}

Student:

package com.wielun.arraylist;

public class Student {
    private String studyId;
    private String name;
    private int age;
    private String className;

    public Student() {
    }

    public Student(String studyId, String name, int age, String className) {
        this.studyId = studyId;
        this.name = name;
        this.age = age;
        this.className = className;
    }

    public String getStudyId() {
        return studyId;
    }

    public void setStudyId(String studyId) {
        this.studyId = studyId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }
}

result:

20220221	wielun1	24	Java一班
20220222	wielun2	25	Python一班
20220223	wielun3	26	Golang一班
20220224	wielun4	27	运维一班
student num: 
20220221
20220221	wielun1	24	Java一班
student num: 
2022022
无此人

Guess you like

Origin blog.csdn.net/Dream_ya/article/details/122960047