Java入门(三)之面向对象、String、集合

一、面向对象之定义类


1、创建一个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、创建一个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();
    }
}

结果:

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

二、面向对象语法


1、构造器

有参数构造器(默认存在):初始化的对象时,成员变量的数据均采用默认值
有参数构造器:在初始化对象的时候,同时可以为对象进行赋值
任何类定义出来,默认就自带了无参数构造器,写不写都有
一旦定义了有参数构造器,无参数构造器就没有了,此时就需要自己写一个无参数构造器

(1)创建一个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)创建一个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);
    }
}

结果:

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

2、this关键字

作用:出现在成员方法、构造器中代表当前对象的地址,用于访问当前对象的成员变量、成员方法

(1)创建一个Car
package com.wielun;

public class Car {
    String name;
    double price;

    public Car(String name, double price) {
        this.name = name;
        this.price = price;
    }
}
(2)创建一个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);
    }
}

结果:

领克03
17.5

三、面向对象之三大特征


1、封装

一般对成员变量使用private(私有)关键字修饰进行隐藏,private修饰后改成员变量就只能在当前类中访问
提供public修饰的公开的getter、setter方法暴露其取值和赋值
封装好处:

  • 加强了程序代码的安全性
  • 适当的封装可以提升开发效率,同时可以让程序更容易理解与维护
(1)创建一个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)创建一个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());
    }
}

结果:

年龄不合法
0

2、JavaBean

可以理解成实体类,其对象可以用于在程序中封装数据
成员变量使用private修饰
提供每一个成员变量对应的setXxx()/getXxx()

(1)创建一个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)创建一个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());
    }
}

结果:

wielun
175.0
100.0
wielun1
170.0
1000.0

四、String


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

1、概述

  • java.lang.String类代表字符串,String类定义的变量可以用于指向字符串对象,然后操作该字符串

  • Java程序中的所有字符串文字(例如“wielun”)都为此类的对象

  • String其实常被称为不可变字符串类型,它的对象在创建后不能被更改

2、初体验

package com.wielun.string;

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

结果:

wielun123

3、登陆案例

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、隐私号码案例

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);
    }
}

五、集合ArrayList


1、简介

  • 集合是与数组类似,也是一种容器,用于装数据的

  • 集合的大小不固定,启动后可以动态变化,类型也可以选择不固定

  • 集合非常适合做元素个数不确定,且要进行增删操作的业务场景

2、初体验

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);
    }
}

结果:

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

3、泛型之初体验

ArrayList:其实就是一个泛型类,可以在编译阶段约束集合对象只能操作某种数据类型

package com.wielun.arraylist;

import java.util.ArrayList;

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

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

结果:

[Java, Python]
[23, 21]

4、泛型之常用方法

package com.wielun.arraylist;

import java.util.ArrayList;

public class ArrayListDemo3 {
    public static void main(String[] args) {
        ArrayList 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);
    }
}

结果:

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、电影案例

package com.wielun.arraylist;

import java.util.ArrayList;

public class ArrayListTest5 {
    public static void main(String[] args) {
        // 1.定义一个电影类: Movie
        // 2.定义一个ArrayList集合存储这些影片对象
        ArrayList 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());
        }
    }
}

Moive:

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;
    }
}

结果:

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

6、学生搜索案例

package com.wielun.arraylist;

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

public class ArrayListTest6 {
    public static void main(String[] args) {
        // 1.定义一个学生类,后期用于创建对象封装学生数据
        // 2.定义一个集合对象用于装学生对象
        ArrayList 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 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;
    }
}

结果:

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
无此人

你可能感兴趣的:(Java,java,开发语言,后端)