java基础代码,适合0基础学习者

方法

**定义方法练习

练习一

比较两个整数是否相同

  • 分析:定义方法实现功能,需要有两个明确,即返回值参数列表
    • 明确返回值:比较整数,比较的结果只有两种可能,相同或不同,因此结果是布尔类型,比较的结果相同为true。
    • 明确参数列表:比较的两个整数不确定,所以默认定义两个int类型的参数。
public class Method_Demo3 {
    public static void main(String[] args) {
        //调用方法compare,传递两个整数
        //并接收方法计算后的结果,布尔值
        boolean bool = compare(3, 8);
        System.out.println(bool);
    }

    /*
        定义比较两个整数是否相同的方法
        返回值类型,比较的结果布尔类型
        参数:不确定参与比较的两个整数
    */
    public static boolean compare(int a, int b) {
        if (a == b) {
            return true;
        } else {
            return false;
        }
    }
}
练习二

计算1+2+3…+100的和

  • 分析:定义方法实现功能,需要有两个明确,即返回值参数
    • 明确返回值:1~100的求和,计算后必然还是整数,返回值类型是int
    • 明确参数:需求中已知到计算的数据,没有未知的数据,不定义参数
public class Method_Demo4 {
    public static void main(String[] args) {
        //调用方法getSum
        //并接收方法计算后的结果,整数
        int sum = getSum();
        System.out.println(sum);
    }

    /*
        定义计算1~100的求和方法
        返回值类型,计算结果整数int
        参数:没有不确定数据
    */
    public static int getSum() {
        //定义变量保存求和
        int sum = 0;
        //从1开始循环,到100结束
        for (int i = 1; i <= 100; i++) {
            sum = sum + i;
        }
        return sum;
    }
}

练习三

实现不定次数打印

  • 分析:定义方法实现功能,需要有两个明确,即返回值参数

    • 明确返回值:方法中打印出HelloWorld即可,没有计算结果,返回值类型void

    • 明确参数:打印几次不清楚,参数定义一个整型参数\

      public class Method_Demo5 {
          public static void main(String[] args) {
              //调用方法printHelloWorld,传递整数
              printHelloWorld(9);
          }
      
          /*
                定义打印HelloWorld方法
                返回值类型,计算没有结果 void
                参数:不确定打印几次
          */
          public static void printHelloWorld(int n) {
              for (int i = 0; i < n; i++) {
                  System.out.println("HelloWorld");
              }
          }
      }
      

**方法重载练习

练习一

比较两个数据是否相等。参数类型分别为两个byte类型,两个short类型,两个int类型,两个long类型,并在main方法中进行测试。

public class Method_Demo6 {
    public static void main(String[] args) {
        //定义不同数据类型的变量
        byte a = 10;
        byte b = 20;
        short c = 10;
        short d = 20;
        int e = 10;
        int f = 10;
        long g = 10;
        long h = 20;
        // 调用
        System.out.println(compare(a, b));
        System.out.println(compare(c, d));
        System.out.println(compare(e, f));
        System.out.println(compare(g, h));
    }

    // 两个byte类型的
    public static boolean compare(byte a, byte b) {
        System.out.println("byte");
        return a == b;
    }

    // 两个short类型的
    public static boolean compare(short a, short b) {
        System.out.println("short");
        return a == b;
    }

    // 两个int类型的
    public static boolean compare(int a, int b) {
        System.out.println("int");
        return a == b;
    }

    // 两个long类型的
    public static boolean compare(long a, long b) {
        System.out.println("long");
        return a == b;
    }
}

练习二

判断哪些方法是重载关系。

public static void open(){}
public static void open(int a){}
static void open(int a,int b){}// 冲突
public static void open(double a,int b){}
public static void open(int a,double b){}// 冲突
public void open(int i,double d){}  // 冲突
public static void OPEN(){}// 不是重载  方法名不一致
public static void open(int i,int j){}// 冲突
练习三

模拟输出语句中的println方法效果,传递什么类型的数据就输出什么类型的数据,只允许定义一个方法名println

public class Method_Demo7 {
	public static void println(byte a) {
        System.out.println(a);
    }

    public static void println(short a) {
        System.out.println(a);
    }

    public static void println(int a) {
        System.out.println(a);
    }

    public static void println(long a) {
        System.out.println(a);
    }

    public static void println(float a) {
        System.out.println(a);
    }

    public static void println(double a) {
        System.out.println(a);
    }

    public static void println(char a) {
        System.out.println(a);
    }

    public static void println(boolean a) {
        System.out.println(a);
    }

    public static void println(String a) {
        System.out.println(a);
    }
}

**方法调用

练习一

比较两个整数是否相同

  • 分析:定义方法实现功能,需要有两个明确,即返回值参数列表
    • 明确返回值:比较整数,比较的结果只有两种可能,相同或不同,因此结果是布尔类型,比较的结果相同为true。
    • 明确参数列表:比较的两个整数不确定,所以默认定义两个int类型的参数。
public class Method_Demo3 {
    public static void main(String[] args) {
        //调用方法compare,传递两个整数
        //并接收方法计算后的结果,布尔值
        boolean bool = compare(3, 8);
        System.out.println(bool);
    }

    /*
        定义比较两个整数是否相同的方法
        返回值类型,比较的结果布尔类型
        参数:不确定参与比较的两个整数
    */
    public static boolean compare(int a, int b) {
        if (a == b) {
            return true;
        } else {
            return false;
        }
    }
}

练习二

计算1+2+3…+100的和

  • 分析:定义方法实现功能,需要有两个明确,即返回值参数
    • 明确返回值:1~100的求和,计算后必然还是整数,返回值类型是int
    • 明确参数:需求中已知到计算的数据,没有未知的数据,不定义参数
public class Method_Demo4 {
    public static void main(String[] args) {
        //调用方法getSum
        //并接收方法计算后的结果,整数
        int sum = getSum();
        System.out.println(sum);
    }

    /*
        定义计算1~100的求和方法
        返回值类型,计算结果整数int
        参数:没有不确定数据
    */
    public static int getSum() {
        //定义变量保存求和
        int sum = 0;
        //从1开始循环,到100结束
        for (int i = 1; i <= 100; i++) {
            sum = sum + i;
        }
        return sum;
    }
}

练习三

实现不定次数打印

  • 分析:定义方法实现功能,需要有两个明确,即返回值参数
    • 明确返回值:方法中打印出HelloWorld即可,没有计算结果,返回值类型void
    • 明确参数:打印几次不清楚,参数定义一个整型参数
public class Method_Demo5 {
    public static void main(String[] args) {
        //调用方法printHelloWorld,传递整数
        printHelloWorld(9);
    }

    /*
          定义打印HelloWorld方法
          返回值类型,计算没有结果 void
          参数:不确定打印几次
    */
    public static void printHelloWorld(int n) {
        for (int i = 0; i < n; i++) {
            System.out.println("HelloWorld");
        }
    }
}

数组

**数组遍历

  • 就是将数组中的每个元素分别获取出来,就是遍历。遍历也是数组操作中的基石。
public static void main(String[] args) {
    int[] arr = { 1, 2, 3, 4, 5 };
    System.out.println(arr[0]);
    System.out.println(arr[1]);
    System.out.println(arr[2]);
    System.out.println(arr[3]);
    System.out.println(arr[4]);
}

以上代码是可以将数组中每个元素全部遍历出来,但是如果数组元素非常多,这种写法肯定不行,因此我们需要改造成循环的写法。数组的索引是0lenght-1 ,可以作为循环的条件出现。

public static void main(String[] args) {
    int[] arr = { 1, 2, 3, 4, 5 };
    for (int i = 0; i < arr.length; i++) {
      System.out.println(arr[i]);
    }
}

**数组获取最大值

练习: 获取int[] arr = { 5, 15, 2000, 10000, 100, 4000 }的最大值

  • 定义一个存储最大值变量(选美临时待定区),保存数组0索引上的元素
  • 遍历数组,获取出数组中的每个元素
  • 将遍历到的元素和用来存储最大值的变量进行比较
  • 如果数组元素的值大于了变量的值,变量记录住新的值
  • 数组循环遍历结束,变量保存的就是数组中的最大值
public static void main(String[] args) {
    int[] arr = { 5, 15, 2000, 10000, 100, 4000 };
    //定义变量,保存数组中0索引的元素
    int max = arr[0];
    //遍历数组,取出每个元素
    for (int i = 0; i < arr.length; i++) {
      //遍历到的元素和变量max比较
      //如果数组元素大于max
      if (arr[i] > max) {
        //max记录住大值
        max = arr[i];
      }
    }
    System.out.println("数组最大值是: " + max);
}

**数组反转

数组中的元素:10 20 30 40 50

反转之后数组中的元: 50 40 30 20 10

数组的反转: 数组中的元素颠倒顺序,例如原始数组为1,2,3,4,5,反转后的数组为5,4,3,2,1

**实现思想:**数组最远端的元素互换位置。

  • 实现反转,就需要将数组最远端元素位置交换
  • 循环遍历数组,遍历次数为: arr.length/2
  • 拿索引为i的元素与索引为 数组长度-1-i 的元素互换
// 数组互换
    public static void main(String[] args) {

//        int[] arr = {10,20,30,40,50};
        int[] arr = {10,20,30,40,50,60};
        // 需求:对arr数组中的元素进行反转 {50,40,30,20,10}
        // 互换
        for (int i = 0;i<arr.length/2;i++){
            // 互换: arr[i]  与 arr[arr.length-1-i]
            int temp = arr[i];
            arr[i] = arr[arr.length-1-i];
            arr[arr.length-1-i] = temp;
        }

        // 遍历输出数组中的元素
        for (int i = 0;i<arr.length;i++){
            System.out.println(arr[i]);
        }

    }

**数组作为方法参数

1.定义一个方法,方法的参数类型为数组类型, 例如: int数组类型 int[]

public static void main(String[] args) {
    int[] arr = { 1, 3, 5, 7, 9 };
    //调用方法,传递数组
    printArray(arr);
}
/*
	创建方法,方法接收数组类型的参数
	进行数组的遍历
*/
public static void printArray(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
      System.out.println(arr[i]);
    }
}

注意:数组作为方法参数传递,传递的参数是数组内存的地址。

**数组作为方法返回值

2.定义一个方法,方法的返回值类型为数组类型,例如:int数组类型 int[]

public static void main(String[] args) {
    //调用方法,接收数组的返回值
    //接收到的是数组的内存地址
    int[] arr = getArray();
    for (int i = 0; i < arr.length; i++) {
      System.out.println(arr[i]);
    }
}
/*
	创建方法,返回值是数组类型
	return返回数组的地址
*/
public static int[] getArray() {
    int[] arr = { 1, 3, 5, 7, 9 };
    //返回数组的地址,返回到调用者
    return arr;
}

注意:数组作为方法的返回值,返回的是数组的内存地址

类与对象、封装、构造方法

**类与对象

案例:定义一个学生类

分析:

​ 1.类名: Student

​ 2.成员变量: 学号 ,姓名,年龄,成绩,性别

​ 3.成员方法: 学习的功能…

类的定义格式举例:

public class Student {
  	//成员变量
  	String name;//姓名
    int age;//年龄

    //成员方法
    //学习的方法
    publicvoid study() {
    System.out.println("好好学习,天天向上");
  }

  //吃饭的方法
  publicvoid eat() {
    System.out.println("学习饿了要吃饭");
  }
}

**对象使用格式

创建对象:

类名 对象名 = new 类名();

使用对象访问类中的成员:

对象名.成员变量;
对象名.成员方法()

对象的使用格式举例:

public class Test01_Student {
  public static void main(String[] args) {
    //创建对象格式:类名 对象名 = new 类名();
    Student s = new Student();
    System.out.println("s:"+s); //cn.itcast.Student@100363

    //直接输出成员变量值
    System.out.println("姓名:"+s.name); //null
    System.out.println("年龄:"+s.age); //0
    System.out.println("----------");

    //给成员变量赋值
    s.name = "赵丽颖";
    s.age = 18;

    //再次输出成员变量的值
    System.out.println("姓名:"+s.name); //赵丽颖
    System.out.println("年龄:"+s.age); //18
    System.out.println("----------");

    //调用成员方法
    s.study(); // "好好学习,天天向上"
    s.eat(); // "学习饿了要吃饭"
  }	
}

类与对象的练习

定义手机类:

public class Phone {
  // 成员变量
  String brand; //品牌
  int price; //价格
  String color; //颜色

  // 成员方法
  //打电话
  public void call(String name) {
    System.out.println("给"+name+"打电话");
  }

  //发短信
  public void sendMessage() {
    System.out.println("群发短信");
  }
}

定义测试类:

public class Test02Phone {
  public static void main(String[] args) {
    //创建对象
    Phone p = new Phone();

    //输出成员变量值
    System.out.println("品牌:"+p.brand);//null
    System.out.println("价格:"+p.price);//0
    System.out.println("颜色:"+p.color);//null
    System.out.println("------------");

    //给成员变量赋值
    p.brand = "锤子";
    p.price = 2999;
    p.color = "棕色";

    //再次输出成员变量值
    System.out.println("品牌:"+p.brand);//锤子
    System.out.println("价格:"+p.price);//2999
    System.out.println("颜色:"+p.color);//棕色
    System.out.println("------------");

    //调用成员方法
    p.call("紫霞");
    p.sendMessage();
  }
}

##** 标准代码——JavaBean

JavaBean 是 Java语言编写类的一种标准规范。符合JavaBean 的类,要求类必须是具体的和公共的,并且具有无参数的构造方法,提供用来操作成员变量的setget 方法。

public class ClassName{
  //成员变量
  //构造方法
  //无参构造方法【必须】
  //有参构造方法【建议】
  //成员方法	
  //getXxx()
  //setXxx()
}

编写符合JavaBean 规范的类,以学生类为例,标准代码如下:

public class Student {
  //成员变量
  private String name;
  private int age;

  //构造方法
  public Student() {}

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

  //成员方法
  publicvoid setName(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  publicvoid setAge(int age) {
    this.age = age;
  }

  publicint getAge() {
    return age;
  }
}

测试类,代码如下:

public class TestStudent {
  public static void main(String[] args) {
    //无参构造使用
    Student s= new Student();
    s.setName("柳岩");
    s.setAge(18);
    System.out.println(s.getName()+"---"+s.getAge());

    //带参构造使用
    Student s2= new Student("赵丽颖",18);
    System.out.println(s2.getName()+"---"+s2.getAge());
  }
}

对象、集合

**Scanner类

创建对象,使用对象访问成员变量和成员方法

一个可以解析基本类型和字符串的简单文本扫描器。
例如,以下代码使用户能够从 System.in 中读取一个数:

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

备注:System.in 系统输入指的是通过键盘录入数据。

练习:使用Scanner类,完成接收键盘录入数据的操作,代码如下:

//1. 导包
import java.util.Scanner;
public class Demo01_Scanner {
  	public static void main(String[] args) {
    	//2. 创建键盘录入数据的对象
    	Scanner sc = new Scanner(System.in);

    	//3. 接收数据
    	System.out.println("请录入一个整数:");
    	int i = sc.nextInt();

    	//4. 输出数据
    	System.out.println("i:"+i);
  	}
}
scanner类练习

练习一

键盘录入两个数据并求和,代码如下:

import java.util.Scanner;
public class Test01Scanner {
  public static void main(String[] args) {
    // 创建对象
    Scanner sc = new Scanner(System.in);
    // 接收数据
    System.out.println("请输入第一个数据:");
    int a = sc.nextInt();
    System.out.println("请输入第二个数据:");
    int b = sc.nextInt();
    // 对数据进行求和
    int sum = a + b;
    System.out.println("sum:" + sum);
  }
}

练习二

键盘录入三个数据并获取最大值,代码如下:

import java.util.Scanner;
public class Test02Scanner {
  public static void main(String[] args) {
    // 创建对象
    Scanner sc = new Scanner(System.in);
    // 接收数据
    System.out.println("请输入第一个数据:");
    int a = sc.nextInt();
    System.out.println("请输入第二个数据:");
    int b = sc.nextInt();
    System.out.println("请输入第三个数据:");
    int c = sc.nextInt();

    // 如何获取三个数据的最大值
    int temp = (a > b ? a : b);
    int max = (temp > c ? temp : c);

    System.out.println("max:" + max);
  }
}

**Random类

此类的实例用于生成伪随机数。

例如,以下代码使用户能够得到一个随机数:

Random r = new Random();
int i = r.nextInt();

使用Random类,完成生成3个10以内的随机整数的操作,代码如下:

//1. 导包
import java.util.Random;
public class Demo01_Random {
  	public static void main(String[] args) {
        //2. 创建键盘录入数据的对象
        Random r = new Random();

        for(int i = 0; i < 3; i++){
            //3. 随机生成一个数据
            int number = r.nextInt(10);
            //4. 输出数据
            System.out.println("number:"+ number);
        }		
    }
}

注意:public int nextInt(int n):返回一个伪随机数,范围在[0,10)

Random类练习

练习一

获取1-n之间的随机数,包含n,代码如下:

// 导包
import java.util.Random;
public class Test01Random {
  public static void main(String[] args) {
    int n = 50; 	
    // 创建对象
    Random r = new Random();
    // 获取随机数
    int number = r.nextInt(n) + 1;
    // 输出随机数
    System.out.println("number:" + number);
  }
}

练习二

游戏开始时,会随机生成一个1-100之间的整数number 。玩家猜测一个数字guessNumber ,会与number 作比较,系统提示大了或者小了,直到玩家猜中,游戏结束。

// 导包
import java.util.Random;
public class Test02Random {
  public static void main(String[] args) {
    // 系统产生一个随机数1-100之间的。
    Random r = new Random();
    int number = r.nextInt(100) + 1;
    while(true){
      // 键盘录入我们要猜的数据
      Scanner sc = new Scanner(System.in);
      System.out.println("请输入你要猜的数字(1-100):");
      int guessNumber = sc.nextInt();

      // 比较这两个数据(用if语句)
      if (guessNumber > number) {
        System.out.println("你猜的数据" + guessNumber + "大了");
      } else if (guessNumber < number) {
        System.out.println("你猜的数据" + guessNumber + "小了");
      } else {
        System.out.println("恭喜你,猜中了");
        break;
      }
    }
  }
}

ArrayList类

ArrayList练习

格式: 集合 ArrayList list = new ArrayList<>();

练习一

生成6个1~33之间的随机整数,添加到集合,并遍历

public class Test01ArrayList {
  public static void main(String[] args) {
    // 创建Random 对象
    Random random = new Random();

    // 创建ArrayList 对象
    ArrayList<Integer> list = new ArrayList<>();

    // 添加随机数到集合
    for (int i = 0; i < 6; i++) {
      int r = random.nextInt(33) + 1;
      list.add(r);
    }

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

练习二

自定义4个学生对象,添加到集合,并遍历 (添加对象到集合)

public class Test02ArrayList {
  public static void main(String[] args) {
    //创建集合对象
    ArrayList<Student> list = new ArrayList<Student>();

    //创建学生对象
    Student s1 = new Student("赵丽颖",18);
    Student s2 = new Student("唐嫣",20);
    Student s3 = new Student("景甜",25);
    Student s4 = new Student("柳岩",19);

    //把学生对象作为元素添加到集合中
    list.add(s1);
    list.add(s2);
    list.add(s3);
    list.add(s4);

    //遍历集合
    for(int x = 0; x < list.size(); x++) {
      Student s = list.get(x);
      System.out.println(s.getName()+"---"+s.getAge());
    }
  }
}

练习三

打印集合方法

定义以指定格式打印集合的方法(ArrayList类型作为参数),使用{}扩起集合,使用@分隔每个元素。格式参照 {元素@元素@元素}。

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

    // 添加字符串到集合中
    list.add("张三丰");
    list.add("宋远桥");
    list.add("张无忌");
    list.add("殷梨亭");

    // 调用方法
    printArrayList(list);
  }

  public static void printArrayList(ArrayList<String> list) {
    // 拼接左括号
    System.out.print("{");
    // 遍历集合
    for (int i = 0; i < list.size(); i++) {
      // 获取元素
      String s = list.get(i);
      // 拼接@符号
      if (i != list.size() - 1) {
        System.out.print(s + "@");
      } else {
        // 拼接右括号
        System.out.print(s + "}");
      }
    }
  }
}

练习四

获取集合方法

定义获取所有偶数元素集合的方法(ArrayList类型作为返回值)

public class Test04ArrayList {
  public static void main(String[] args) {
    // 创建Random 对象
    Random random = new Random();
    // 创建ArrayList 对象
    ArrayList<Integer> list = new ArrayList<>();

    // 添加随机数到集合
    for (int i = 0; i < 20; i++) {
      int r = random.nextInt(1000) + 1;
      list.add(r);
    }
    // 调用偶数集合的方法
    ArrayList<Integer> arrayList = getArrayList(list);
    System.out.println(arrayList);
  }

  public static ArrayList<Integer> getArrayList(ArrayList<Integer> list) {
    // 创建小集合,来保存偶数
    ArrayList<Integer> smallList = new ArrayList<>();

    // 遍历list
    for (int i = 0; i < list.size(); i++) {
      // 获取元素
      Integer num = list.get(i);
      // 判断为偶数,添加到小集合中
      if (num % 2 == 0){
        smallList.add(num);
      }
    }
    // 返回小集合
    return smallList;
  }
}

String类、static关键字、Arrays类、Math类

**String类

特点

1.字符串不变:字符串的值在创建后不能被更改。

String s1 = "abc";
s1 += "d";
System.out.println(s1); // "abcd" 
// 内存中有"abc","abcd"两个对象,s1从指向"abc",改变指向,指向了"abcd"。

2.String常量字符串,是可以被共享的。

String s1 = "abc";
String s2 = "abc";
// 内存中只有一个"abc"对象被创建,同时被s1和s2共享。

3."abc" 等效于 char[] data={ 'a' , 'b' , 'c' }

例如: 
String str = "abc";

相当于: 
char[] data = {'a', 'b', 'c'};     
String str = new String(data);
// String底层是靠字符数组实现的。
判断功能的方法
  • public boolean equals (Object anObject) :将此字符串与指定对象进行比较。

  • public boolean equalsIgnoreCase (String anotherString) :将此字符串与指定对象进行比较,忽略大小写。

    方法演示,代码如下:

     public static void main(String[] args) {
             /*
                判断功能的方法
                    - public boolean equals (Object anObject) :将此字符串与指定对象进行比较。
                    - public boolean equalsIgnoreCase (String anotherString) :将此字符串与指定对象进行比较,忽略大小写。
    
                tips: Object 是” 对象”的意思,也是一种引用类型。作为参数类型,表示任意对象都可以传递到方法中
             */
            //  public boolean equalsIgnoreCase (String anotherString)
            // 1.创建一个字符串对象
            String str1 = "hello";
    
            // 2.创建一个字符串对象
            String str2 = "Hello";
    
            // 3.使用equalsIgnoreCase()方法比较str1和str2字符串是否相等
            boolean res1 = str1.equalsIgnoreCase(str2);
            System.out.println("res1的值是:"+res1);// true
        }
    
        /**
         * 演示 boolean equals (Object anObject)
         */
        private static void method01() {
            // - public boolean equals (Object anObject) :将此字符串与指定对象进行比较。
            // 1.创建一个字符串对象
            String str1 = "hello";
    
            // 2.创建一个字符串对象
            String str2 = "Hello";
    
            // 3.使用equals方法比较str1和str2这2个字符串是否相等
            boolean res1 = str1.equals(str2);
            System.out.println("res1的值是:" + res1);// false
    
    
            // 扩展:
            // 创建一个字符串对象
            String str3 = new String("hello");
    
            // 使用equals方法比较str1与str3这2个字符串是否相等
            boolean res2 = str1.equals(str3);
            System.out.println("res2的值是:" + res2);// true equals()方法比较的是2个字符串的内容是否相等
            System.out.println(str1 == str3);// false  == 比较的是2个字符串对象的地址值是否相等
        }
    

Object 是” 对象”的意思,也是一种引用类型。作为参数类型,表示任意对象都可以传递到方法中。

  • 如果想要比较2个字符串是否相等,那么就使用equals方法,千万别用 == 比较
获取功能的方法
  • public int length () :返回此字符串的长度。
  • public String concat (String str) :将指定的字符串连接到该字符串的末尾。
  • public char charAt (int index) :返回指定索引处的 char值。
  • public int indexOf (String str) :返回指定子字符串第一次出现在该字符串内的索引。
  • public String substring (int beginIndex) :返回一个子字符串,从beginIndex开始截取字符串到字符串结尾。
  • public String substring (int beginIndex, int endIndex) :返回一个子字符串,从beginIndex到endIndex截取字符串。含beginIndex,不含endIndex。

方法演示,代码如下:

public class String_Demo02 {
     public static void main(String[] args) {
        /*
        获取功能的方法
            - public int length () :返回此字符串的长度。
            - public String concat (String str) :将指定的字符串连接到该字符串的末尾。
            - public char charAt (int index) :返回指定索引处的 char值。
            - public int indexOf (String str) :返回指定子字符串第一次出现在该字符串内的索引。
            - int lastIndexOf(String str)  返回指定子字符串在此字符串中最右边出现处的索引。
            - public String substring (int beginIndex) :返回一个子字符串,从beginIndex开始截取字符串到字符串结尾。
            - public String substring (int beginIndex, int endIndex) :返回一个子字符串,从beginIndex到endIndex截取字符串。含beginIndex,不含endIndex。
         */
        // 1.创建一个字符串对象
        String str1 = "hello-world!";

        // - public int length () :返回此字符串的长度。
        int len = str1.length();
        System.out.println("str1的长度是:"+len);//str1的长度是:12

        // - public String concat (String str) :将指定的字符串连接到该字符串的末尾。拼接字符串
        String newStr = str1.concat(" 世界,你好!");
        System.out.println("str1的值是:"+str1);// hello world!  字符串是不可变的
        System.out.println("newStr的值是:"+newStr);// hello world! 世界,你好!


        // - public char charAt (int index) :返回指定索引处的 char值。
        // 获取str1字符串中1索引位置对于的元素
        char ch = str1.charAt(1);
        System.out.println("str1字符串中1索引位置对于的元素:"+ch);// e

        // 获取str1字符串的最后一个字符
        char ch2 = str1.charAt(len-1);
        System.out.println("str1字符串的最后一个字符:"+ch2);// !

        // public int indexOf (String str) :返回指定子字符串第一次出现在该字符串内的索引
        // 获取"world"子字符串在str1字符串中第一次出现的索引
        int index = str1.indexOf("world");
        System.out.println("world子字符串在str1字符串中第一次出现的索引:"+index);// 6

        // 获取"l"子字符串在str1字符串中第一次出现的索引
        int index2 = str1.indexOf("l");
        System.out.println("l子字符串在str1字符串中第一次出现的索引:"+index2);// 2

        // 获取"l"子字符串在str1字符串中最后一次出现的索引
        int index3 = str1.lastIndexOf("l");
        System.out.println("l子字符串在str1字符串中最后一次出现的索引:"+index3);// 9

        //- public String substring (int beginIndex) :返回一个子字符串,从beginIndex开始截取字符串到字符串结尾。
        // 截取str1字符串中的:world!
        String subStr1 = str1.substring(6);
        System.out.println("subStr1的值是:"+subStr1);// world!

        // - public String substring (int beginIndex, int endIndex) :返回一个子字符串,从beginIndex到endIndex截取字符串。含beginIndex,不含endIndex。
        // 截取str1字符串中的:hello
        String subStr2 = str1.substring(0, 5);
        System.out.println("subStr2的值是:"+subStr2);

    }
}
转换功能的方法
  • public char[] toCharArray () :将此字符串转换为新的字符数组。
  • public byte[] getBytes () :使用平台的默认字符集将该 String编码转换为新的字节数组。
  • public String replace (CharSequence target, CharSequence replacement) :将与target匹配的字符串使用replacement字符串替换。

方法演示,代码如下:

  public static void main(String[] args) {
        /*
            转换功能的方法
                - public char[] toCharArray () :将此字符串转换为新的字符数组。
                - public byte[] getBytes () :使用平台的默认字符集将该 String编码转换为新的字节数组。
                - public String replace (CharSequence target, CharSequence replacement) :将与target匹配的字符串使用replacement字符串替换。
                tips:CharSequence 是一个接口,也是一种引用类型。作为参数类型,可以把String对象传递到方法中。
                    简而言之:如果参数的类型是CharSequence,那么就可以传入字符串对象
         */
        // 创建一个字符串对象
        String str1 = "abcdefg";

        // 1. - public char[] toCharArray () :将此字符串转换为新的字符数组。
        // 把str1字符串转换为字符数组
        char[] chs = str1.toCharArray();// {'a','b','c','d','e','f','g'}

        // 遍历chs字符数组
        for (int i = 0; i < chs.length; i++) {
            System.out.print(chs[i]+" ");
        }

        System.out.println();
        System.out.println("==========================");

        //  2.- public byte[] getBytes () :使用平台的默认字符集将该 String编码转换为新的字节数组。
        // 把str1字符串转换为byte[]数组(字节数组)
        byte[] bys = str1.getBytes();

        // 遍历bys字节数组
        for (int i = 0; i < bys.length; i++) {
            System.out.print(bys[i]+" ");
        }

        System.out.println();
        System.out.println("==========================");

        // 3.public String replace (CharSequence target, CharSequence replacement) :将与target匹配的字符串使用replacement字符串替换。
        // 使用nba替换str1中的abc
        String newStr = str1.replace("abc", "nba");
        System.out.println("str1的值是:"+str1);// abcdefg
        System.out.println("newStr的值是:"+newStr);// nbadefg


    }

CharSequence 是一个接口,也是一种引用类型。作为参数类型,可以把String对象传递到方法中。

分割功能的方法
  • public String[] split(String regex) :将此字符串按照给定的regex(规则)拆分为字符串数组。

方法演示,代码如下:

public class String_Demo03 {
    public static void main(String[] args) {
        /*
            分割功能的方法
                - public String[] split(String regex) :将此字符串按照给定的regex(规则)拆分为字符串数组。
         */
        // 1.特殊字符
        // 创建一个字符串
        String str = "aa|bb|cc";

        // - public String[] split(String regex) :将此字符串按照给定的regex(规则)拆分为字符串数组。
        // 以|拆分str字符串----> 拆分后得到: aa bb cc
        String[] arr = str.split("\\|");

        System.out.println("arr数组的长度:"+arr.length);
        // 遍历split数组
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }

        System.out.println("================");
        // 2.没有特殊字符
        // 创建一个字符串
        String str2 = "aa,bb,cc";

        // - public String[] split(String regex) :将此字符串按照给定的regex(规则)拆分为字符串数组。
        // 以,拆分str字符串----> 拆分后得到: aa bb cc
        String[] arr2 = str2.split(",");

        System.out.println("arr2数组的长度:"+arr2.length);
        // 遍历split数组
        for (int i = 0; i < arr2.length; i++) {
            System.out.println(arr2[i]);
        }
    }
}
练习一

定义一个方法,把数组{1,2,3}按照指定个格式拼接成一个字符串。格式参照如下:[word1#word2#word3]。

public class StringTest1 {
  public static void main(String[] args) {
        /*
            拼接字符串
                定义一个方法,把数组{10,20,30}按照指定个格式拼接成一个字符串。格式参照如下:[word1#word2#word3]。
         */
        int[] arr = {10,20,30};
        
        // 调用appendArray()方法
        String s = appendArray(arr);
        System.out.println("s:"+s);//[10#20#30]
    }

    public static String appendArray(int[] arr) {
        // 1. 定义一个字符串str,字符的内容是左中括号: [
        String str = "[";

        // 2. 遍历数组
        for (int i = 0; i < arr.length; i++) {
            // 3. 获取数组元素
            int e = arr[i];

            // 4. 判断元素是否是最后一个元素
            if (i == arr.length - 1) {
                // 5. 如果是最后一个元素,就使用str拼接上: 元素+]
                str += e + "]";
            } else {
                // 6. 如果不是最后一个元素,就使用str拼接上: 元素+#
                str += e + "#";
            }
        }
        // 7. 把拼接后的字符串返回
        return str;
    }
}
练习二

键盘录入一个字符串,统计字符串中大小写字母及数字字符个数

public class StringTest2 {
  public static void main(String[] args) {
    //键盘录入一个字符串数据
    Scanner sc = new Scanner(System.in);
    System.out.println("请输入一个字符串数据:");
    String s = sc.nextLine();

    //定义三个统计变量,初始化值都是0
    int bigCount = 0;
    int smallCount = 0;
    int numberCount = 0;

    //遍历字符串,得到每一个字符
    for(int x=0; x<s.length(); x++) {
      char ch = s.charAt(x);
      //拿字符进行判断
      if(ch>='A'&&ch<='Z') {
        bigCount++;
      }else if(ch>='a'&&ch<='z') {
        smallCount++;
      }else if(ch>='0'&&ch<='9') {
        numberCount++;
      }else {
        System.out.println("该字符"+ch+"非法");
      }
    }

    //输出结果
    System.out.println("大写字符:"+bigCount+"个");
    System.out.println("小写字符:"+smallCount+"个");
    System.out.println("数字字符:"+numberCount+"个");
  }
}

**Arrays类

操作数组的方法
  • public static String toString(int[] a) :返回指定数组内容的字符串表示形式。
public static void main(String[] args) {
  // 定义int 数组
  int[] arr  =  {2,34,35,4,657,8,69,9};
  // 打印数组,输出地址值
  System.out.println(arr); // [I@2ac1fdc4

  // 数组内容转为字符串
  String s = Arrays.toString(arr);
  // 打印字符串,输出内容
  System.out.println(s); // [2, 34, 35, 4, 657, 8, 69, 9]
}
  • public static void sort(int[] a) :对指定的 int 型数组按数字升序进行排序。
public static void main(String[] args) {
  // 定义int 数组
  int[] arr  =  {24, 7, 5, 48, 4, 46, 35, 11, 6, 2};
  System.out.println("排序前:"+ Arrays.toString(arr)); // 排序前:[24, 7, 5, 48, 4, 46, 35, 11, 6, 2]
  // 升序排序
  Arrays.sort(arr);
  System.out.println("排序后:"+ Arrays.toString(arr));// 排序后:[2, 4, 5, 6, 7, 11, 24, 35, 46, 48]
}
练习一

请使用Arrays 相关的API,将一个随机字符串中的所有字符升序排列,并倒序打印。

public class ArraysTest {
  public static void main(String[] args) {
    // 定义随机的字符串
    String line = "ysKUreaytWTRHsgFdSAoidq";
    // 转换为字符数组
    char[] chars = line.toCharArray();

    // 升序排序
    Arrays.sort(chars);
    // 反向遍历打印
    for (int i =  chars.length-1; i >= 0 ; i--) {
      System.out.print(chars[i]+" "); // y y t s s r q o i g e d d a W U T S R K H F A 
    }
  }
}

**Math类

基本运算的方法
  • public static double abs(double a) :返回 double 值的绝对值。
double d1 = Math.abs(-5); //d1的值为5
double d2 = Math.abs(5); //d2的值为5
  • public static double ceil(double a) :返回大于等于参数的最小的整数。
double d1 = Math.ceil(3.3); //d1的值为 4.0
double d2 = Math.ceil(-3.3); //d2的值为 -3.0
double d3 = Math.ceil(5.1); //d3的值为 6.0
  • public static double floor(double a) :返回小于等于参数最大的整数。
double d1 = Math.floor(3.3); //d1的值为3.0
double d2 = Math.floor(-3.3); //d2的值为-4.0
double d3 = Math.floor(5.1); //d3的值为 5.0
  • public static long round(double a) :返回最接近参数的 long。(相当于四舍五入方法)
long d1 = Math.round(5.5); //d1的值为6.0
long d2 = Math.round(5.4); //d2的值为5.0
练习

请使用Math 相关的API,计算在 -10.85.9 之间,绝对值大于6 或者小于2.1 的整数有多少个?

public class MathTest {
  public static void main(String[] args) {
    // 定义最小值
    double min = -10.8;
    // 定义最大值
    double max = 5.9;
    // 定义变量计数
    int count = 0;
    // 范围内循环
    for (double i = Math.ceil(min); i <= max; i++) {
      // 获取绝对值并判断
      if (Math.abs(i) > 6 || Math.abs(i) < 2.1) {
        // 计数
        count++;
      }
    }
    System.out.println("个数为: " + count + " 个");
  }
}

**static关键字

static修饰成员变量------>类变量

格式

static 数据类型 变量名;

举例

public class Person {
    // 非静态变量
    String name;
    // 静态变量
    static String country;    
}

访问静态变量:

类名.静态变量名

对象名.静态变量名

// 测试类
public static void main(String[] args) {

    Person p1 = new Person();
    p1.name = "张无忌";
    p1.country = "中国";
    // 姓名:张无忌,国籍:中国
    System.out.println("姓名:"+p1.name+",国籍:"+p1.country);

    Person p2 = new Person();
    // 姓名:null,国籍:中国
    System.out.println("姓名:"+p2.name+",国籍:"+p2.country);
	
    // 类名.静态成员变量名
    System.out.println(Person.country);// 中国
}
static修饰成员方法---->静态方法
  • 类方法概述:使用 static关键字修饰的成员方法,习惯称为静态方法
  • 定义格式
修饰符 static 返回值类型 方法名 (参数列表){ 
	// 执行语句 
}
  • 举例:在Student类中定义静态方法
public class Student {
    // 静态方法
    public static void method1(){
        System.out.println("静态方法method1执行了...");
    }

    public static void method2(){
        System.out.println("静态方法method2执行了...");
    }

}

访问方式

类名.静态方法名(实参);

对象名.静态方法名(实参);

    public static void main(String[] args) {

        // 调用静态方法:
        // 类名.静态方法名(实参);
        Student.method1();

        // 对象名.静态方法名(实参);
        Student stu = new Student();
        stu.method2();
    }
静态代码块

静态代码块:定义在成员位置,使用static修饰的代码块{ }。

位置:类中方法外。

执行:随着类的加载而执行且执行一次,优先于main方法和构造方法的执行。

格式:

public class ClassName{
  static {
    // 执行语句 
  }
}

演示:

public class Person {
    // 静态代码块
    static {
        System.out.println("Person类中的静态代码块");
    }

    public Person(){
        System.out.println("Person类中的构造方法");
    }

}

//测试类:
public class Demo6 {

    static {
        System.out.println("Demo6中的静态代码块");
    }

    public static void main(String[] args) {

        System.out.println("这是main方法中的代码");
	    new Person();// 匿名对象
    }
}


作用:给类变量进行初始化赋值。用法演示,代码如下:

public class Game {
  public static int number;
  public static ArrayList<String> list;

  static {
    // 给类变量赋值
    number = 2;
    list = new ArrayList<String>();
    // 添加元素到集合中
    list.add("张三");
    list.add("李四");
  }
}

小贴士:

static 关键字,可以修饰变量、方法和代码块。在使用的过程中,其主要目的还是想在不创建对象的情况下,去调用方法。下面将介绍两个工具类,来体现static 方法的便利。

静态方法调用的注意事项
public class Student {
    String name;// 非静态变量
    static String country;// 静态变量

    // 静态方法
    public static void method1(){
        // 静态方法可以直接访问静态变量和静态方法
        System.out.println("访问静态变量:"+country);
        method2();// 访问静态方法

        // 静态方法不能直接访问普通成员变量或成员方法
        System.out.println("访问非静态变量:"+name); // 报错
        method3();//访问非静态方法   报错

        // 静态方法中,不能使用this关键字。
        System.out.println(this.country);// 报错
        System.out.println(this.name);// 报错

        System.out.println("静态方法method1执行了...");
    }

    public static void method2(){
        System.out.println("静态方法method2执行了...");
    }

    // 非静态方法
     // 非静态方法
    public  void method3(){
        // 非静态成员方法可以直接访问类变量或静态方法。
        System.out.println("访问非静态成员变量:"+name);
        System.out.println("访问静态成员变量:"+country);

        // 访问非静态方法
        method4();
        // 访问静态方法
        method2();

        System.out.println("method3方法执行了...");
    }

    public  void method4(){
        System.out.println("非静态方法method4执行了...");
    }

}

继承、super、this、抽象类

**继承

通过 extends 关键字,可以声明一个子类继承另外一个父类,定义格式如下:

class 父类 {
	...
}

class 子类 extends 父类 {
	...
}

继承演示,代码如下:

/*
 * 定义员工类Employee,做为父类
 */
class Employee {
	String name; // 定义name属性
	// 定义员工的工作方法
	public void work() {
		System.out.println("尽心尽力地工作");
	}
}

/*
 * 定义讲师类Teacher 继承 员工类Employee
 */
class Teacher extends Employee {
	// 定义一个打印name的方法
	public void printName() {
		System.out.println("name=" + name);
	}
}

/*
 * 定义测试类
 */
public class ExtendDemo01 {
	public static void main(String[] args) {
        // 创建一个讲师类对象
		Teacher t = new Teacher();
      
        // 为该员工类的name属性进行赋值
		t.name = "小明"; 
      
      	// 调用该员工的printName()方法
		t.printName(); // name = 小明
		
      	// 调用Teacher类继承来的work()方法
      	t.work();  // 尽心尽力地工作
	}
}

成员变量不重名

如果子类父类中出现不重名的成员变量,这时的访问是没有影响的。代码如下:

class Fu {
	// Fu中的成员变量。
	int num = 5;
}
class Zi extends Fu {
	// Zi中的成员变量
	int num2 = 6;
	// Zi中的成员方法
	public void show() {
		// 访问父类中的num,
		System.out.println("Fu num="+num); // 继承而来,所以直接访问。
		// 访问子类中的num2
		System.out.println("Zi num2="+num2);
	}
}
class ExtendDemo02 {
	public static void main(String[] args) {
        // 创建子类对象
		Zi z = new Zi(); 
      	// 调用子类中的show方法
		z.show();  
	}
}

演示结果:
Fu num = 5
Zi num2 = 6
成员变量重名

如果子类父类中出现重名的成员变量,这时的访问是有影响的。代码如下:

class Fu {
	// Fu中的成员变量。
	int num = 5;
}
class Zi extends Fu {
	// Zi中的成员变量
	int num = 6;
	public void show() {
		// 访问父类中的num
		System.out.println("Fu num=" + num);
		// 访问子类中的num
		System.out.println("Zi num=" + num);
	}
}
class ExtendsDemo03 {
	public static void main(String[] args) {
      	// 创建子类对象
		Zi z = new Zi(); 
      	// 调用子类中的show方法
		z.show(); 
	}
}
演示结果:
Fu num = 6
Zi num = 6

子父类中出现了同名的成员变量时,在子类中需要访问父类中非私有成员变量时,需要使用super 关键字,修饰父类成员变量,类似于之前学过的 this

使用格式:

super.父类成员变量名

子类方法需要修改,代码如下:

class Zi extends Fu {
	// Zi中的成员变量
	int num = 6;
	public void show() {
		//访问父类中的num
		System.out.println("Fu num=" + super.num);
		//访问子类中的num
		System.out.println("Zi num=" + this.num);
	}
}
演示结果:
Fu num = 5
Zi num = 6

小贴士:Fu 类中的成员变量是非私有的,子类中可以直接访问。若Fu 类中的成员变量私有了,子类是不能直接访问的。通常编码时,我们遵循封装的原则,使用private修饰成员变量,那么如何访问父类的私有成员变量呢?对!可以在父类中提供公共的getXxx方法和setXxx方法。

继承后的特点——成员方法
成员方法不重名

如果子类父类中出现不重名的成员方法,这时的调用是没有影响的。对象调用方法时,会先在子类中查找有没有对应的方法,若子类中存在就会执行子类中的方法,若子类中不存在就会执行父类中相应的方法。代码如下:

class Fu{
	public void show(){
		System.out.println("Fu类中的show方法执行");
	}
}
class Zi extends Fu{
	public void show2(){
		System.out.println("Zi类中的show2方法执行");
	}
}
public  class ExtendsDemo04{
	public static void main(String[] args) {
		Zi z = new Zi();
     	//子类中没有show方法,但是可以找到父类方法去执行
		z.show(); 
		z.show2();
	}
}

成员方法重名——重写(Override)

如果子类父类中出现重名的成员方法,这时的访问是一种特殊情况,叫做方法重写 (Override)。

  • 方法重写 :子类中出现与父类一模一样的方法时(返回值类型,方法名和参数列表都相同),会出现覆盖效果,也称为重写或者复写。声明不变,重新实现

代码如下:

class Fu {
	public void show() {
		System.out.println("Fu show");
	}
}
class Zi extends Fu {
	//子类重写了父类的show方法
	public void show() {
		System.out.println("Zi show");
	}
}
public class ExtendsDemo05{
	public static void main(String[] args) {
		Zi z = new Zi();
     	// 子类中有show方法,只执行重写后的show方法
		z.show();  // Zi show
	}
}

重写方法的引用场景:

子类可以根据需要,定义特定于自己的行为。既沿袭了父类的功能名称,又根据子类的需要重新实现父类方法,从而进行扩展增强。比如新的手机增加来电显示头像的功能,代码如下:

class Phone {
	public void sendMessage(){
		System.out.println("发短信");
	}
	public void call(){
		System.out.println("打电话");
	}
	public void showNum(){
		System.out.println("来电显示号码");
	}
}

//智能手机类
class NewPhone extends Phone {
	
	//重写父类的来电显示号码功能,并增加自己的显示姓名和图片功能
	public void showNum(){
		//调用父类已经存在的功能使用super
		super.showNum();
		//增加自己特有显示姓名和图片功能
		System.out.println("显示来电姓名");
		System.out.println("显示头像");
	}
}

public class ExtendsDemo06 {
	public static void main(String[] args) {
      	// 创建子类对象
      	NewPhone np = new NewPhone()// 调用父类继承而来的方法
        np.call();
      
      	// 调用子类重写的方法
      	np.showNum();

	}
}

小贴士:这里重写时,用到super.父类成员方法,表示调用父类的成员方法。

继承后的特点——构造方法

首先我们要回忆两个事情,构造方法的定义格式和作用。

  1. 构造方法的名字是与类名一致的。所以子类是无法继承父类构造方法的。
  2. 构造方法的作用是初始化成员变量的。所以子类的初始化过程中,必须先执行父类的初始化动作。子类的构造方法中默认有一个super() ,表示调用父类的构造方法,父类成员变量初始化后,才可以给子类使用。代码如下:
class Fu {
  private int n;
  Fu(){
    System.out.println("Fu()");
  }
}
class Zi extends Fu {
  Zi(){
    // super(),调用父类构造方法
    super();
    System.out.println("Zi()");
  }  
}
public class ExtendsDemo07{
  public static void main (String args[]){
    Zi zi = new Zi();
  }
}
输出结果:
Fu()
Zi()

super和this的含义
  • super :代表父类的存储空间标识(可以理解为父亲的引用)。

  • this :代表当前对象的引用(谁调用就代表谁)。

super和this的用法
  1. 访问成员
this.成员变量    	--    本类的
super.成员变量    	--    父类的

this.成员方法名()  	--    本类的    
super.成员方法名()   --    父类的

用法演示,代码如下:

class Animal {
    public void eat() {
        System.out.println("animal : eat");
    }
}
 
class Cat extends Animal {
    public void eat() {
        System.out.println("cat : eat");
    }
    public void eatTest() {
        this.eat();   // this  调用本类的方法
        super.eat();  // super 调用父类的方法
    }
}
 
public class ExtendsDemo08 {
    public static void main(String[] args) {
        Animal a = new Animal();
        a.eat();
        Cat c = new Cat();
        c.eatTest();
    }
}

输出结果为:
animal : eat
cat : eat
animal : eat
  1. 访问构造方法
this(...)    	--    本类的构造方法
super(...)   	--    父类的构造方法

子类的每个构造方法中均有默认的super(),调用父类的空参构造。手动调用父类构造会覆盖默认的super()。

super() 和 this() 都必须是在构造方法的第一行,所以不能同时出现。

继承的特点
  1. Java只支持单继承,不支持多继承。
//一个类只能有一个父类,不可以有多个父类。
class C extends A{} 	//ok
class C extends A,B...	//error
  1. Java支持多层继承(继承体系)。
class A{}
class B extends A{}
class C extends B{}
  1. 子类拥有父类的成员变量和成员方法
  2. 子类只能直接访问父类的非私有成员,不能直接访问私有成员(成员变量和成员方法),间接访问私有成员
    1. 访问父类的私有成员变量 通过set\get方法
    2. 访问父类的私有成员方法 通过其他公共的方法

定义格式:

修饰符 abstract 返回值类型 方法名 (参数列表)

代码举例:

public abstract void run()

**抽象类

如果一个类包含抽象方法,那么该类必须是抽象类。

定义格式:

abstract class 类名字 { 
  
}

代码举例:

public abstract class Animal {
    public abstract void run()}
抽象的使用

继承抽象类的子类必须重写父类所有的抽象方法。否则,该子类也必须声明为抽象类。最终,必须有子类实现该父类的抽象方法,否则,从最初的父类到最终的子类都不能创建对象,失去意义。

代码举例:

public class Cat extends Animal {
    public void run (){
      	System.out.println("小猫在墙头走~~~")}
}

public class CatTest {
 	 public static void main(String[] args) {
        // 创建子类对象
        Cat c = new Cat(); 
       
        // 调用run方法
        c.run();
  	}
}
输出结果:
小猫在墙头走~~~

此时的方法重写,是子类对父类抽象方法的完成实现,我们将这种方法重写的操作,也叫做实现方法

**发红包综合案例

定义用户类:

public class User {
    private String name;// 姓名
    private int leftMoney;// 余额

    public User() {
    }

    public User(String name, int leftMoney) {
        this.name = name;
        this.leftMoney = leftMoney;
    }

    public String getName() {
        return name;
    }

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

    public int getLeftMoney() {
        return leftMoney;
    }

    public void setLeftMoney(int leftMoney) {
        this.leftMoney = leftMoney;
    }

    public void show(){
        System.out.println("我是:"+name+",我的余额是:"+leftMoney);
    }

}

定义群主类:

import java.util.ArrayList;

public class QunZhu extends User {

    public QunZhu() {
    }

    public QunZhu(String name, int leftMoney) {
        super(name, leftMoney);
    }

    // 发红包
    /*
        明确方法返回值类型:  ArrayList<Integer>
        明确方法名:   faHongBao
        明确方法参数:  红包金额 int  红包个数 int
        明确方法体:
           10元  5包   每个包2元
           10元  3包   3  3  3
     */
    public ArrayList<Integer> faHongBao(int redMoney,int count){
        // 0.创建一个集合用来存储这多个小红包
        ArrayList<Integer> list = new ArrayList<>();

        // 1.获取群主余额
        int leftMoney = getLeftMoney();

        // 2.判断是否够发红包  余额 >= 红包金额
        if (leftMoney < redMoney){
        // 3.如果不够发红包,就返回null
            return null;
        }else{
        // 4.如果够发红包,就发红包
            //  4.0 群主的余额要减少
            setLeftMoney(getLeftMoney() - redMoney);
        // 4.1 求这多个红包的平均金额
            int avg = redMoney / count;

        // 4.2 求除不尽剩余的金额
            int left = redMoney % count;

        // 4.3 把count-1个平均红包添加到集合中
            for (int i = 0;i<count-1;i++){
                list.add(avg);
            }
        // 4.4 把除不尽剩余的金额 加上 一个平均红包 添加到集合中
            list.add(avg+left);
        }
        // 5. 返回集合
        return list;
    }
}

定义成员类:

import java.util.ArrayList;
import java.util.Random;

public class QunYuan extends User {
    public QunYuan() {
    }

    public QunYuan(String name, int leftMoney) {
        super(name, leftMoney);
    }

    // 抢红包的功能
     /*
        明确方法返回值类型:  void
        明确方法名:   qiangHongBao
        明确方法参数:  ArrayList<Integer>
        明确方法体:
     */
     public void qiangHongBao(ArrayList<Integer> list){
         // 随机抽取一个红包  集合是根据索引取元素,所以就随机产生一个索引
         // 创建随机生成器
         Random r = new Random();

         // 随机产生一个索引 [0,list.size-1]
         int index = r.nextInt(list.size());//[0]  ---0
         System.out.println(index);

         // 根据产生随机索引去list集合中取出红包
         Integer redMoney = list.get(index);

         // 要删除刚刚取出来的红包金额元素
         list.remove(index);

         // 把抢到的红包金额添加到自己的余额中
         setLeftMoney(getLeftMoney() + redMoney);
     }
}

定义测试类:

public class Demo12 {
    public static void main(String[] args) {
        QunZhu qz = new QunZhu("群主",10);

        QunYuan qy1 = new QunYuan("群员1",0);
        QunYuan qy2 = new QunYuan("群员2",0);
        QunYuan qy3 = new QunYuan("群员3",0);

        // 群主发红包
        ArrayList<Integer> list = qz.faHongBao(10, 3);
        // {4}
        // 群员抢红包
        qy1.qiangHongBao(list);// list集合的长度是3
        qy2.qiangHongBao(list);// list集合的长度是2
        qy3.qiangHongBao(list);// list集合的长度是1

        // 显示信息
        qz.show();
        qy1.show();
        qy2.show();
        qy3.show();

    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值