day03--Basic Java programming: object-oriented, construction methods, code block explanations, this super, static, final, access modifiers, method overriding, up_down modeling, main method, abstract class, interface, design pattern, exception, inner class

1 Day06 – Object Oriented 1

1.1 Object-oriented

1.1.1 Concept

Recommended book : Thinking in java

Concept : The so-called object-oriented is a programming idea, through which complex things in life can be simplified, from the original executor to the commander. Object-oriented is based on process-oriented.

The advantages and disadvantages of process-oriented structured design :
1). Disadvantages: lack of data encapsulation.
2). Disadvantages: Data and methods (for operating data) are difficult to separate.
3). Advantages: relatively high performance.

Advantages and disadvantages of object-oriented design :
1). Advantages: easy to maintain, easy to expand, and easy to reuse.
2). Disadvantages: performance is lower than process-oriented.

Process-oriented emphasizes the process , for example:
1. Open the refrigerator 2. Put the elephant in 3. Close the refrigerator

Object-oriented emphasizes results , for example:
1. If you are hungry, go to the platform to order food. This action is object-oriented. You didn’t go to the market to buy vegetables, wash them, and cook them. . . As long as you have the app.
2. If the clothes are dirty, just leave them to the female to deal with them and wait for clean ones to be worn. You don't pay attention to the middle process. . Just find a good partner.
3. The interviewer asked what is object-oriented? You answer that everything is an object! ! I don’t recommend it because you haven’t reached this depth yet. It’s best to give an example. It's like, if you say that emptiness is form and form is emptiness - believe me.

what we often sayobject-oriented programmingaccomplish(OOP,Object Oriented Programming

The essence of object-oriented is to organize code in the form of classes and encapsulate data in the form of objects.

1.1.2 Three major characteristics

1. Encapsulation : Encapsulation realizes "high cohesion and low coupling" of software components, preventing the impact of program changes due to dependencies.
(1) Class: encapsulates the properties and behavior of the object
(2) Method: encapsulates the implementation of specific business logic functions
(3) Access control modifier: encapsulates specific access rights

2. Inheritance : Inheritance improves the reusability and scalability of software.
(1) Function: facilitate code reuse, reduce code redundancy, and improve program maintainability and scalability
(2) Super class: attributes and behaviors common to all derived classes Interface: behavioral derivation
common to some derived classes
Class: attributes and behaviors unique to derived classes
(3) There is single inheritance between classes, multiple inheritance between interfaces, and multiple implementations between classes and interfaces.

3. Polymorphism : Polymorphism enhances the flexibility and scalability of software.
(1) Classification:
(1.1) Behavioral polymorphism (can give examples)
(1.2) Object polymorphism (can give examples)
(2) Upcasting, forced type conversion, instanceof judgment
(3) Polymorphic expressions
(3.1) Rewrite: express polymorphism according to different objects
(3.2) Overloading: express polymorphism according to different parameters

1.1.3 Extension: Pass by value and pass by reference

Specification: A project should have only one main startup class
java is pass by value

package com.shuai;

public class Demo01 {
    
    
    //值传递
    public static void main(String[] args) {
    
    
        int a = 1;
        System.out.println(a);//1
        change(a);
        System.out.println(a);//1  没有修改成功
    }
    public static void change(int a) {
    
     //返回值为空,就没有返回值
        a=10;

    }
}

1.2 Classes and Objects

1.2.1 Class

1. Java language is the mostbasic unitIt's a class, similar to a type.
2. A class is an abstraction of a type of thing. (Category/type, representing a type of individual)
3. Can be understood as a template or design drawing .
4. Classes in the same package can be used with each other, but cannot have the same name (must be saved).
5. Syntax: class class name { }
6. Classes generally include :

  1. Properties/Characteristics common to all objects--------Member variables
  2. Behavior common to all objects ------- methods

Classes in the same package can be accessed directly, but classes in different packages cannot be accessed directly. If you want to access :

  1. First import declare a full name class (package name + class name), and then access the class (that is, new an object)
  2. Accessing the full name of the class ------- is too cumbersome and not recommended (it is too troublesome to write one statement each)

Note : There can be multiple classes in a .java file, but it is required that there can only be one public-modified class, and the class name is the file name (case-sensitive, and there is no need for a public-modified class). Different files can have multiple publics. When Chu Ti is written, different files may be written together, so multiple publics can be written.

1.2.2 Object

Object : A real individual.

Each object has three characteristics : the object'sstate, objectBehaviorand objectlogo

1. The state of an object is used to describe the basic characteristics of the object.
2. The behavior of an object is used to describe the function of the object.
3. The identification of an object means that the object has a unique address in the memory to distinguish it from other objects.
4. A class is an abstraction of a type of thing, and an object is a concrete implementation.
5. Syntax: new class name ();
6. Each new will create a new object.
7. After using the new keyword to create an object and allocate space, it will do two things: default initialization (assigning default values ​​to variables) and calling the constructor.

Calling member variables and methods (when creating an object) :

引用类型的名字.局部变量名 = 赋值;
引用类型的名字.方法调用的方式;

Why create an object : Because access means accessing things, variables and methods in the class, because only after instantiation can the object be placed in memory and then called within the specified range.

1.2.3 Relationship between classes and objects

1. Computer language is used to describe things in the real world.Properties + behavior
2. How to describe it through java language?Describe things through classes, regard the attributes of things as 成员变量, and regard behaviors as成员方法.
3. A class can create multiple objects.

Summary : A class is a template for an object, and an object is a specific instance of the class.

Take mobile phones as an example :

属性:颜色,尺寸,品牌,价格。
方法:打电话,发短信,听音乐。
类:手机类,抽取相同的属性和行为
对象:可以按照模板生产很多个手机,比如1号手机对象,包含特有的成员变量和成员方法

Insert image description here

1.3 Creation and use of classes and objects

1.3.1 Exercise 1: Creating and using classes

Create a class through the class keyword and create an object through the new keyword
1).

public class Test1_CreateObject {
    
    
    public static void main(String[] args) {
    
    
       //创建对象测试
       //3,通过关键字new来创建对象
       //new Phone()匿名对象,一次只干一个活
       //new Phone().call();  只能干一件事
       //4,p是Phone类型是引用类型的变量,引用了,,,内存中的地址值
       Phone p = new Phone();
 
      //引用类型的创建,引用类型的默认值是null,引用类型与它需要实例的对象类名一致。
       //p代表了Phone对象,真的能用模板定义的功能吗???
       //调用方法
       p.call();
       p.message();
       p.music();
      
       //设置属性值
       p.color="green";   //调用的时候改值
       p.size=6;
       p.pinpai="HUAWEI";
       p.price=20000;
      
       //调用属性
       System.out.println(p.color);//null --green
       System.out.println(p.size);//0 -- 6
       System.out.println(p.pinpai);//null  --HUAWEI
       System.out.println(p.price);//0.0  --20000.0
      
    }
   
}
//1,创建手机类,用来描述手机事物
//2,通常描述:事物的特征+事物的行为
class Phone{
    
    
//  事物的特征    --  成员变量/成员属性
//  特征:颜色,尺寸,品牌,价格
    String color;
    int size;
    String pinpai;
    double price;
   
//  事物的行为    --  成员方法/成员函数
//  行为/功能:打电话,发短信,听音乐
    //修饰符  返回值  方法名(参数列表){方法体}
    public void call() {
    
    
       System.out.println("call()...");
    }
    public void message() {
    
    
       System.out.println("message()...");
    }
    public void music() {
    
    
       System.out.println("music()...");
    }
   
}

2).

package cn.tedu.oop;
//练习
public class Test2_Car {
    
    
    public static void main(String[] args) {
    
    
       //2,创建Car对象测试
       Car c =  new Car();
      
       //调用功能
       c.run();
       c.stop();
      
       //设置属性值
       c.color="red";
       c.model="BMW5";
       c.pinpai="BMW";
      //直接输出变量
       System.out.println(c.color);
       System.out.println(c.model);
       System.out.println(c.pinpai);
    }
}
 
//1,创建Car类,用来描述汽车事物
class Car{
    
    
//  -- 特征+行为
    String color;
    String model;
    String pinpai;
   
    public void run() {
    
    
       System.out.println("正在飞");
    }
    public void stop() {
    
    
       System.out.println("停车");
    }
   
}

1.3.2 Storage of objects in memory

Java divides memory into five major areas. The memory is managed by the JVM. We focus on the stack and heap.
Insert image description here

  1. Generally speaking, local variables are stored on the stack, and the memory is released after the method is executed (the stack is smaller than the heap)
  2. Objects (new things) are stored in the heap. When the object is no longer used, the memory will be released.
  3. Each element of heap memory has an address value
  4. All properties in the object have default values.
  5. Address values ​​are unique and will not be repeated (storing address values ​​takes up less memory space and costs less)
  6. The stack is: first in, last out principle (similar to loading a bullet). Heap: Without this principle, you can put it anywhere.
  7. The memory is managed by the JVM: the class is loaded first, then the .class is allocated in the method area, then the heap is allocated, and then the stack is allocated (the stack and heap start almost at the same time)
  8. The object has an address value only after it has been initialized.
  9. Stack: released after the method is executed. Heap: Releases memory when called without any references.

What are stored in the stack, heap, and method area?

Stack : Local variables (including method parameters, also called local variables), store the address value of a corresponding object.
Heap : new objects (including instance variables and methods).
Method area : .class bytecode file (static method and static variable) in the class, which is only loaded once.

1.3.3 Single object memory graph

Insert image description here

Noun : pop out

1.3.4 Exercise 2: Creating multiple objects

package cn.tedu.oop;
 
//测试多个对象的创建和使用
public class Test3_Person {
    
    
       public static void main(String[] args) {
    
    
              //创建对象测试 (addr:地址  brand:品牌)
              Person p = new Person();
              p.game(); //调用方法的时候可以传参赋值
              p.code();
              //设置属性值:在调用属性的时候赋值
              p.name="rose";
              p.age=20;
              p.gender=1;
              p.address="北京";
              //打印
              System.out.println(p.name);
              System.out.println(p.age);
              System.out.println(p.gender);
              System.out.println(p.address);
            
              /*如果创建了一个类的多个对象,则每个对象都独立的拥有一套类的属性。(非static的)
              意味着:如果我们修改一个对象的属性a,则不影响另外一个对象属性a的值。*/
              Person p2 = new Person();
              p2.code();
              p2.game();
             
              //TODO 设置属性值
              System.out.println(p2.name);//null
              System.out.println(p2.age);
              System.out.println(p2.gender);
              System.out.println(p2.address);
 
              //p3是引用类型的变量,这里没有new,在堆内存中就不会开辟新空间。
              //p3保存了p2保存着的地址值
              Person p3 = p2;
       }
}
//创建Person类
class Person{
    
    
       //特征
       String name;
       int age;
       int gender;//0男1女
       String address;
      
       //行为
       public void code() {
    
    
              System.out.println("敲代码");
       }
       public void game() {
    
    
              System.out.println("吃鸡");
       }
}

1.3.5 Multi-object memory graph

Insert image description here

1. Variable p and variable p2 are not the same space. p1 needs to open up a new space.
2. Person p2=new Person. At this time, as long as there is new, a new space will be opened to store the object in the heap memory.

1.4 Packaging

1.4.1 Overview

Encapsulation refers to hiding the properties and implementation details of an object and only providing public access to the outside world.
Benefits :
1. Improve security
2. Improve reusability
Cases :
1. Class
2. Method

1.4.2 private keyword

is a permission modifier used to modifyMember variables and member functions, privatized members can only be accessed within this class. If you want to modify, you can only access the externally provided public get (value acquisition) and set (assignment) methods. In the past, you could directly call the 对象.资源assignment through , but now you can only perform the assignment operation through the set method or the constructor method . Of course, just calling or 对象.资源making a call .

Encapsulation, implemented using the private keyword, aims to improve security, this class.
For example: a public int age. The outside world can call it at will and assign a value of 10,000 years old, which is obviously unreasonable. Variables that want to be modified with private can only be called by accessing the public modified method. We can add some restrictions in the method, but we cannot add them to the variable.

General encapsulation: properties ( member variables ) are privatized and behaviors (methods) are made public.

1.4.3 Exercise 1: Encapsulating students

Create student class and create student object test

package cn.tedu.oop;
//测试封装
public class Test4_Private {
    
    
       public static void main(String[] args) {
    
    
              //创建学生对象测试
              Student s = new Student();
             
              //调用功能
//           s.study();//由于study()被private修饰了,除了自己的类,别的类都用不了
              s.sleep();
             
//           System.out.println(s.name);//由于name被private修饰了,除了自己的类,别的类都用不了
             
              //3,如果我就是想要修改已经被private的name属性的值? --访问公共的set()
//           s.name ="jack";//无法访问
              s.setName("jack");  //调用set方法赋值88888888888
             
              //4,如果外界就是想要获取被private的name属性的值? --访问公共的get()
//           System.out.println(s.name) ;//无法访问
              System.out.println(s.getName());//和平常的输出不一样,这个是直接输出的方法。(因为get方法有返回值一般前边是定义一个变量来接受,所以说这个地方可以直接输出方法)
       }
}
//创建学生类
class Student{
    
    
       //成员属性
       //1.1,封装:成员变量,封装好的变量,外界无法直接访问,需要间接访问公共的set()设置值,get()获取值 有快捷键:source------get and set
       private String name;
      
       //3.1,对外提供一个公共的修改方法 -- setXxx() 没有返回值
       public void setName(String n) {
    
    
              //拿到n之后,需要把n的值赋值给name
              name = n;
       }    
       //4.1,对外提供一个公共的获取改方法 -- getXxx() 有返回值
       public String getName(){
    
    
              //4.2,通过return关键字,把name属性的值,返回给调用位置
              return name;
       }
       //TODO  封装以下三个属性,并提供set()/get()
       private String subject;
       public void setSubject(String s) {
    
    
              subject = s ;
       }
       public String getSubject() {
    
    
              return subject;
       }
      
       private int sno;
       private int age;
      
       //eclipse自动生成代码:右键-source-setters and getters-select all-ok
       public int getSno() {
    
    
              return sno;
       }
       public void setSno(int sno) {
    
    
              this.sno = sno;
       }
       public int getAge() {
    
    
              return age;
       }
       public void setAge(int age) {
    
    
              this.age = age;
       }
      
       //成员方法
       //1,封装:利用private关键字实现,目的就是提高代码的安全性,被private之后,资源只能在本类中看见
       private void study() {
    
    
              System.out.println("正在学习");
       }
       public void sleep() {
    
    
       //2,如果外界还是想执行study(),可以访问公共的sleep(),间接实现访问study()   
              study();
              System.out.println("正在睡觉");
       }
      
      
      
}

1.5 Expansion

1.5.1 Process of creating objects

Person p = new Person();//A lot of things happened in this short line of code
1. Load the Person.class file into memory
2. In the stack memory, open up space to store the variable p
3. In the heap memory, open up Space to store Person objects
4. Default initialization of member variables
5. Display initialization of member variables
6. Execute the construction method (if there is a construction code block, execute the construction code block first and then the construction method)
7. Heap memory is completed
8. Assign the address value of the heap memory to the variable p. p is a reference variable that refers to the address value of the Person object.

1.5.2 Anonymous objects

An object without a name is a simplified representation of an object.
Usage scenario : When the called object is called only once.

advantage: Save memory and have high efficiency. Because it releases the memory immediately after calling it once
shortcoming: Limitation, its attributes can only be used once.

Demo d = new Demo();
d.sleep();
d.game();
//这个d就是对象的名字。
也可以写成:
new Demo().show();//创建了一个对象调方法
new Demo().game();//又创建了一个对象调方法

1.5.3 Declaring an array of object types

package com.atguigu.exer;
/*
 *  对象数组题目:
定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。
 创建20个学生对象,学号为1到20,年级和成绩都由随机数确定。
问题一:打印出3年级(state值为3)的学生信息。
问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息

提示:
1) 生成随机数:Math.random(),返回值类型double;  
2) 四舍五入取整:Math.round(double d),返回值类型long。
 * 
 * 
 * 
 * 
 */
public class StudentTest {
    
    
	public static void main(String[] args) {
    
    
		
//		Student s1 = new Student();
//		Student s1 = new Student();
//		Student s1 = new Student();
//		Student s1 = new Student();
//		Student s1 = new Student();
//		Student s1 = new Student();
		
		//声明Student类型的数组
		Student[] stus = new Student[20];  //String[] arr = new String[10];
		
		for(int i = 0;i < stus.length;i++){
    
    
			//给数组元素赋值
			stus[i] = new Student();
			//给Student对象的属性赋值
			stus[i].number = (i + 1);
			//年级:[1,6]
			stus[i].state = (int)(Math.random() * (6 - 1 + 1) + 1);
			//成绩:[0,100]
			stus[i].score = (int)(Math.random() * (100 - 0 + 1));
		}
		
		//遍历学生数组
		for(int i = 0;i <stus.length;i++){
    
    
//			System.out.println(stus[i].number + "," + stus[i].state 
//					+ "," + stus[i].score);
			
			System.out.println(stus[i].info());
		}
		
		System.out.println("********************");
		
		//问题一:打印出3年级(state值为3)的学生信息。
		for(int i = 0;i <stus.length;i++){
    
    
			if(stus[i].state == 3){
    
    
				System.out.println(stus[i].info());
			}
		}
		
		System.out.println("********************");
		
		//问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息
		for(int i = 0;i < stus.length - 1;i++){
    
    
			for(int j = 0;j < stus.length - 1 - i;j++){
    
    
				if(stus[j].score > stus[j + 1].score){
    
    
					//如果需要换序,交换的是数组的元素:Student对象!!!
					Student temp = stus[j];
					stus[j] = stus[j + 1];
					stus[j + 1] = temp;
				}
			}
		}
		
		//遍历学生数组
		for(int i = 0;i <stus.length;i++){
    
    
			System.out.println(stus[i].info());
		}
		
	}
}

class Student{
    
    
	int number;//学号
	int state;//年级
	int score;//成绩
	
	//显示学生信息的方法
	public String info(){
    
    
		return "学号:" + number + ",年级:" + state + ",成绩:" + score;
	}
	
}

Optimized writing method: encapsulated into an array tool class

package com.atguigu.exer;
/*
 * 4. 对象数组题目:
定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。
 创建20个学生对象,学号为1到20,年级和成绩都由随机数确定。
问题一:打印出3年级(state值为3)的学生信息。
问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息

提示:
1) 生成随机数:Math.random(),返回值类型double;  
2) 四舍五入取整:Math.round(double d),返回值类型long。
 * 
 * 
 * 此代码是对StudentTest.java的改进:将操作数组的功能封装到方法中。
 * 
 */
public class StudentTest1 {
    
    
	public static void main(String[] args) {
    
    
		
		//声明Student类型的数组
		Student1[] stus = new Student1[20];  
		
		for(int i = 0;i < stus.length;i++){
    
    
			//给数组元素赋值
			stus[i] = new Student1();
			//给Student对象的属性赋值
			stus[i].number = (i + 1);
			//年级:[1,6]
			stus[i].state = (int)(Math.random() * (6 - 1 + 1) + 1);
			//成绩:[0,100]
			stus[i].score = (int)(Math.random() * (100 - 0 + 1));
		}
		
		StudentTest1 test = new StudentTest1();
		
		//遍历学生数组
		test.print(stus);
		
		System.out.println("********************");
		
		//问题一:打印出3年级(state值为3)的学生信息。
		test.searchState(stus, 3);
		
		System.out.println("********************");
		
		//问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息
		test.sort(stus);
		
		//遍历学生数组
		test.print(stus);
		
	}
	
	/**
	 * 
	 * @Description  遍历Student1[]数组的操作
	 * @author shkstart
	 * @date 2019年1月15日下午5:10:19
	 * @param stus
	 */
	public void print(Student1[] stus){
    
    
		for(int i = 0;i <stus.length;i++){
    
    
			System.out.println(stus[i].info());
		}
	}
	/**
	 * 
	 * @Description 查找Stduent数组中指定年级的学生信息
	 * @author shkstart
	 * @date 2019年1月15日下午5:08:08
	 * @param stus 要查找的数组
	 * @param state 要找的年级
	 */
	public void searchState(Student1[] stus,int state){
    
    
		for(int i = 0;i <stus.length;i++){
    
    
			if(stus[i].state == state){
    
    
				System.out.println(stus[i].info());
			}
		}
	}
	
	/**
	 * 
	 * @Description 给Student1数组排序
	 * @author shkstart
	 * @date 2019年1月15日下午5:09:46
	 * @param stus
	 */
	public void sort(Student1[] stus){
    
    
		for(int i = 0;i < stus.length - 1;i++){
    
    
			for(int j = 0;j < stus.length - 1 - i;j++){
    
    
				if(stus[j].score > stus[j + 1].score){
    
    
					//如果需要换序,交换的是数组的元素:Student对象!!!
					Student1 temp = stus[j];
					stus[j] = stus[j + 1];
					stus[j + 1] = temp;
				}
			}
		}
	}
	
	
}

class Student1{
    
    
	int number;//学号
	int state;//年级
	int score;//成绩
	
	//显示学生信息的方法
	public String info(){
    
    
		return "学号:" + number + ",年级:" + state + ",成绩:" + score;
	}
	
}

2 Day07 – Object Oriented 2

2.1 Constructor (constructor, builder, constructor, constructor)

2.1.1 Concept

  1. The constructor is a special method that has the same name as the class and has no return value ( not even void ). Ordinary methods can also have the same name as the class, but they are generally not written this way.
  2. The creation of objects is done through the constructor method.
  3. Its main functions are: 1. Complete the creation of objects. 2. Object properties can be initialized
  4. The constructor is automatically called when a class instantiates an object.
  5. Constructors, like other methods, can be overloaded, but cannot be overridden. (Because: 1. The constructor cannot be inherited: if inherited, it will be the same as the subclass class name. 2. Because there is super in the subclass, it automatically calls the constructor of the parent class)
  6. If you do not define a constructor, a parameterless constructor is provided by default (so any class has a constructor). If you define a constructor, it is no longer provided by default, so it is recommended to write a parameterless constructor manually.
  7. The role of the constructor method: to facilitate the creation of objects by the outside world.

Idea generates constructor method shortcut key: alt+insert.

2.1.2 Form

修饰符  类名([参数列表]){
    
    //可以无参也可以有参

       代码……     
       //没有返回值
}

2.1.3 Exercise 1: Constructor method to create objects

package cn.tedu.constructor;
 
//测试构造方法的使用
public class Test5_Constructor {
    
    
    public static void main(String[] args) {
    
    
       //创建Teacher测试
       //1,当创建对象时,会自动调用构造方法???--会自动调用,调用了默认就会存在的无参构造
       Teacher t = new Teacher();
      
     //3.1,创建对象时,触发含参构造,根据不同的参数类型来自动调用构造方法.
       Teacher t1 = new Teacher("tony");
      
    }
   
}
//创建Teacher类
class Teacher{
    
    
    //2,提供构造方法:修饰符 类名([参数列表]){}
    //4,无参构造  -- 默认就会存在  -- 前提是:没有含参构造时,才存在。如果只提供了含参构造,无参构造就真没了。
    public Teacher() {
    
    
       System.out.println("无参构造...");
    }
   
    //3,构造方法是一个特殊的方法,特殊在没有返回值,方法名=类名。但是可以存在方法的重载现象
    //准备重载的构造方法
    public Teacher(String n) {
    
    
       System.out.println("含参构造..."+n);
    }
   
}

2.1.4 Exercise 2: Constructor initialization assignment

package cn.tedu.constructor;
 
//这个类用来测试构造方法赋值
public class Test6_Constructor2 {
    
    
    public static void main(String[] args) {
    
    
       //自动触发无参构造
       Student2 s = new Student2();
      
       //触发含参构造,在创建对象时给成员变量赋值。
       Student2 s2 = new Student2(2);
    }
}
//创建Student2类
class Student2{
    
    
   
    //成员变量
    int age;
   
    //提供构造方法
    public Student2() {
    
    
       System.out.println("无参构造");
    }
    //提供重载的构造方法

    public Student2(int a) {
    
     //a在方法里面是局部变量
       //1,构造方法可以用来给变量赋值
    //流程:当含参的方式创建对象时,会自动触发含参构造。把参数2给a赋值,a拿到值之后再给成员变量age赋值
       age = a;
       System.out.println("成员变量age:"+age);
       System.out.println("含参构造");
    }
}

2.1.5 Summary: The order of attribute assignment

package com.cn.ca;
/*
 * 总结:属性赋值的先后顺序
 * 
 * 
 * ① 默认初始化(初始化:第一次赋值)
 * ② 显式初始化
 * ③ 构造器中初始化
 * 
 * ④ 通过"对象.方法"(加了private封装控制权限了) 或 "对象.属性"的方式,赋值
 * 
 * 以上操作的先后顺序:① - ② - ③ - ④  
 * 
 */
public class UserTest {
    
    
	public static void main(String[] args) {
    
    
		User u = new User();
		
		System.out.println(u.age);
		
		User u1 = new User(2);
		
		u1.setAge(3);
		u1.setAge(5);
		
		System.out.println(u1.age);
	}
}

class User{
    
    
	String name;//默认初始化
	int age = 1;//显示初始化
	
	public User(){
    
    
		
	}
	
	public User(int a){
    
    //创建对象,属性初始化
		age = a;
	}
	
	public void setAge(int a){
    
    
		age = a;
	}
	
}

2.2 JavaBean reusable components

Insert image description here

package com.atguigu.java1;
/*
 * JavaBean是一种Java语言写成的可重用组件。

	所谓JavaBean,是指符合如下标准的Java类:
		>类是公共的
		>有一个无参的公共的构造器
		>有属性,且有对应的get、set方法

 * 
 */
public class Customer {
    
    
	
	private int id;
	private String name;
	
	public Customer(){
    
    
		
	}
	
	public void setId(int i){
    
    
		id = i;
	}
	public int getId(){
    
    
		return id;
	}
	public void setName(String n){
    
    
		name = n;
	}
	public String getName(){
    
    
		return name;
	}
	
}

2.3 Constructing code blocks and local code blocks

2.3.1 Constructing code blocks

1. Code blocks inside the class and outside the method .
2. Usually used to extract common code in construction methods. You can initialize the properties of the object when creating the object.
3. The construction code block will be called before each call to the construction method
4. Loading takes precedence over the construction method
5.Every time an object is created, the construction code block will be called first, and then the construction method will be called.
6. There can be output statements inside.
7. If multiple non-static code blocks are defined in a class, they will be executed in the order of declaration.
8. Static properties, static methods, or non-static code blocks can be called within the non-static code block. Properties, non-static methods
9, { }

Test construction code block:

package cn.tedu.block;

//1,创建对象时,会自动触发构造方法。如果有构造代码块会先执行代码块再执行构造方法88888888888888888888888888
public class Test1_Block {
    
    
    public static void main(String[] args) {
    
    
       //TODO 创建Person对象测试
       new Person();
       //2,每次创建对象都会调用构造代码块和构造方法
       new Person();
       new Person("name");
       new Person(100);
    }
}
 
//创建Person类
class Person{
    
    
   
    String country;//为了让每个构造方法都使用,提高作用范围
   
    //b,提供构造代码块 : 位置:在类里方法外
    {
    
    
       //3,构造代码块:用来提取构造方法的共性
       country = "中国人";
    }
    //a,提供构造方法
    public Person() {
    
    
       System.out.println("无参构造...,我的国籍是:"+country);
    }
    //c,提供重载构造方法
    public Person(String c) {
    
    
       System.out.println("含参构造...,我的国籍是:"+country);
    }
    public Person(int a) {
    
    
       System.out.println("含参构造...,我的国籍是:"+country);
    }
}

2.3.2 Local code blocks

1. Code blocks in methods (both ordinary methods and constructor methods are acceptable)
2. Usually used to control the scope of variables . If brackets are removed, it will be invalid.
3. The smaller the scope of the variable, the better. Member variables will have thread safety issues.
4.Triggered when method is called
5. Call the local code block when the method is called .
6. { }

2.3.3 Test: Construction, local code block loading order

Construction code block->Construction method->Partial code block

package cn.tedu.block;
//测试代码块
//1,创建对象时,会自动触发构造方法。如果有构造代码块会先执行代码块再执行构造方法,
//若局部代码块写在构造方法里面,构造方法和局部代码块的顺序是看程序写代码的顺序执行。
//若写在普通方法里面,则是调用的时候用(它则是最后用,因为是先创建对象,在通过引用调用方法)。
 
//总结:
//1,构造代码块:创建对象时触发,在类里方法外,用来抽取构造方法的共性
//2,局部代码块:方法调用时触发,在方法里,用来控制变量的作用范围

//若没有创建对象,构造代码块都不会自动执行
//2.每次创建对象都会调用构造代码块和构造方法
public class Test1_Block {
    
    
    public static void main(String[] args) {
    
    
       //TODO 创建Person对象测试
       new Person();
       //2,每次创建对象都会调用构造代码块和构造方法
       new Person();
       new Person("name");
       new Person(100).sleep();//触发局部代码块
    }
}
 
//创建Person类
class Person{
    
    
   
    String country;//为了让每个构造方法都使用,提高作用范围
   
    //b,提供构造代码块 : 位置:在类里方法外
    {
    
    
       //3,构造代码块:用来提取构造方法的共性
       country = "中国人";
    }
    //a,提供构造方法
    public Person() {
    
    
       System.out.println("无参构造...,我的国籍是:"+country);
    }
    //c,提供重载构造方法
    public Person(String c) {
    
    
       System.out.println("含参构造...,我的国籍是:"+country);
    }
    public Person(int a) {
    
    
       System.out.println("含参构造...,我的国籍是:"+country);
    }
   
   
    //提供普通方法
    public void sleep() {
    
    
       //局部代码块: 位置:在方法里 + 作用:控制变量的作用范围
       {
    
    
           int i = 10;
           System.out.println("局部代码块..."+i);
       }
      
//     System.out.println(i);
      
    }
   
   
}

2.4 this keyword

2.4.1 Concept

illustrate:
1. this represents a reference object of this class object.
2. this is only used in two places : one is, when the name of the member variable and the name of the local variable are the same, use this to refer to the member variable to distinguish the difference between the member variable and the local variable. Another one is used to make calls between constructors. Another constructor is used in the first line.

Notice:
1. This can be omitted when the names of member variables and local variables are different .
2. In the constructor, this() must be placed on the first line.

2.4.2 Form

name=name;
age=age;
//解释:其实是想把Student类的局部变量name的值赋值给成员变量,相当于你想操作是这样的:
Student.name=name;
//但是你不能直接写类名,这时候就用代表本类的对象this来完成。代码变成了:
this.name=name;

grammar:

1)this.成员变量名-----------访问成员变量(掌握)
  this.name=name;
2)this.方法名()------------调用方法(不用掌握)
  因为在类中没有相同的方法,所以不用写this来区分。
3)this()------------------调用构造方法(只能重载类名相同)根据它的参数列表
(一个构造方法可以通过this关键字调用另外一个重载的构造方法) 

2.4.3 Exercise 1: When the variable names are the same

Used to distinguish local variables and member variables when they have the same name.
If there is a variable with the same name nearby, the proximity principle of the variable will be followed. So how to call the member variable?

package cn.tedu.thisdemo;
 
//测试this关键字
public class Test2_This {
    
    
    public static void main(String[] args) {
    
    
       //创建Student对象测试
       Student s = new Student();
       s.show();
    }
}
代码体现1//创建Student类
class Student{
    
    
   
    int count ;//成员变量
   
    int sum = 20;//成员变量
   
    public void show() {
    
    
       int sum = 10;//局部变量
      
       System.out.println(sum);//10,就近原则
       System.out.println(count);//0
      
//     System.out.println(new Student().sum);//20
    //1,this关键字代表的是本类对象的一个引用就相当于Student this = new Student();8888888888888888888
    //2,当成员变量和局部变量同名时(如:sum),可以使用this来区分。this调用的是本类的成员变量。888888888888888888888888(当成员变量和局部变量名不同时可以省略this)
//(因为局部变量在方法里,想要调用先调用方法才行,所以它调用的变量是成员变量)
       System.out.println(this.sum);//20
      
    }
   
   
}
 
 
代码体现2class Student2{
    
    
    String name;
    //创建对象时,给成员变量name赋值
    public Student2(String name) {
    
    
//     name = name;//没有成功的给成员变量name赋值,因为等号左右两边都是局部变量    //就近原则
       this.name = name;//等号左边使用的是成员变量,右边是局部变量
//注意:变量只要在方法上就是局部变量,而不是在{ }里才是。
       System.out.println(name);
       System.out.println(this.name);
    }
}

2.4.4 Exercise 2: Calling between constructor methods

package cn.tedu.thisdemo;
//this在构造方法间调用
//总结:this只用在2个地方:一个是,成员变量名和局部变量名相同时,用this指代成员变量用来区分成员变量和局部变量的区别。另一个是,用来构造方法间进行调用另一个构造方法在第一行时用
//1,this可以在构造方法间互相调用
//2,如果在构造方法里出现了this关键字,必须放在第一条语句的位置
//构造方法之间不能同时相互调用,否则会出现死循环,报错。也不能自己调自己。
public class Test3_This2 {
    
    
       public static void main(String[] args) {
    
    
              //无参创建对象测试
              Teacher t = new Teacher();
             
              //含参创建对象测试
              Teacher t2 = new Teacher("jack");
       }
}
//创建Teacher类
class Teacher{
    
    
       //提供构造方法
       public Teacher() {
    
    
              //在 无参构造  中访问 含参构造
//           this("jack");
              System.out.println("无参构造");
       }
      
       public Teacher(String name) {
    
    
              //在 含参构造  中访问 无参构造
              this();             
              System.out.println("含参构造"+name);
       }
      
}

2.4.5 Exercise 3: Comprehensive exercise

package com.atguigu.java2;
/*
 * this关键字的使用:
 * 1.this可以用来修饰、调用:属性、方法、构造器
 * 
 * 2.this修饰属性和方法:
 *   this理解为:当前对象  或 当前正在创建的对象
 * 
 *  2.1  在类的方法中,我们可以使用"this.属性"或"this.方法"的方式,调用当前对象属性或方法。但是,
 *   通常情况下,我们都选择省略"this."。特殊情况下,如果方法的形参和类的属性同名时,我们必须显式
 *   的使用"this.变量"的方式,表明此变量是属性,而非形参。
 * 
 *  2.2 在类的构造器中,我们可以使用"this.属性"或"this.方法"的方式,调用当前正在创建的对象属性或方法。
 *  但是,通常情况下,我们都选择省略"this."。特殊情况下,如果构造器的形参和类的属性同名时,我们必须显式
 *   的使用"this.变量"的方式,表明此变量是属性,而非形参。
 * 
 * 3. this调用构造器
 * 	  ① 我们在类的构造器中,可以显式的使用"this(形参列表)"方式,调用本类中指定的其他构造器
 *    ② 构造器中不能通过"this(形参列表)"方式调用自己
 *    ③ 如果一个类中有n个构造器,则最多有 n - 1构造器中使用了"this(形参列表)"
 *    ④ 规定:"this(形参列表)"必须声明在当前构造器的首行
 *    ⑤ 构造器内部,最多只能声明一个"this(形参列表)",用来调用其他的构造器
 * 
 * 
 */
public class PersonTest {
    
    
	public static void main(String[] args) {
    
    
		
		Person p1 = new Person();
		
		p1.setAge(1);
		System.out.println(p1.getAge());
		
		p1.eat();
		
		System.out.println();
		
		Person p2 = new Person("Jerry",20);
		System.out.println(p2.getAge());
		
	}
}

class Person{
    
    
	
	private String name;
	private int age;
	
	
	public Person(){
    
    
		
//		this.eat();
		String info = "Person初始化时,需要考虑如下的1,2,3,4...(共40行代码)";
		System.out.println(info);
	}
	
	public Person(String name){
    
    
		this();
		this.name = name;
		
	}
	
	public Person(int age){
    
    
		this();
		this.age = age;
		
	}
	
	public Person(String name,int age){
    
    
		this(age);
		this.name = name;
		//this.age = age;
		//Person初始化时,需要考虑如下的1,2,3,4...(共40行代码)
	}
	
	public void setName(String name){
    
    
		this.name = name;
	}
	public String getName(){
    
    
		return this.name;
	}
	public void setAge(int age){
    
    
		this.age = age;
	}
	public int getAge(){
    
    
		return this.age;
	}
	
	public void eat(){
    
    
		System.out.println("人吃饭");
		this.study();
	}
	public void study(){
    
    
		System.out.println("人学习");
	}
	
}

2.5 Use of Package and import keywords

package com.atguigu.java2;

import java.lang.reflect.Field;
import java.util.*;

import com.atguigu.exer4.Account;
import com.atguigu.exer4.Bank;
import com.atguigu.java2.java3.Dog;

import static java.lang.System.*;
import static java.lang.Math.*;

/*
 * 一、package关键字的使用
 * 1.为了更好的实现项目中类的管理,提供包的概念
 * 2.使用package声明类或接口所属的包,声明在源文件的首行(这里的首行要求不严格:指
 *                                  的是声明的第一条语句,在它之前有换行的空格也算是首行)
 * 3.包,属于标识符,遵循标识符的命名规则、规范(xxxyyyzzz)、“见名知意”
 * 4.每"."一次,就代表一层文件目录。
 * 
 * 补充:同一个包下,不能命名同名的接口、类。
 *     不同的包下,可以命名同名的接口、类。
 * 
 * 二、import关键字的使用
 * import:导入
 * 1. 在源文件中显式的使用import结构导入指定包下的类、接口
 * 2. 声明在包的声明和类的声明之间
 * 3. 如果需要导入多个结构,则并列写出即可
 * 4. 可以使用"xxx.*"的方式,表示可以导入xxx包下的所有结构
 * 5. 如果使用的类或接口是java.lang包下定义的,则可以省略import结构
 * 6. 如果使用的类或接口是本包下定义的,则可以省略import结构
 * 7. 如果在源文件中,使用了不同包下的同名的类,则必须至少有一个类需要以全类名的方式显示。
 * 8. 使用"xxx.*"方式表明可以调用xxx包下的所有结构。但是如果使用的是xxx子包下的结构,则仍需要显式导入
 * 
 * 9. import static:导入指定类或接口中的静态结构:属性或方法。 
 */
public class PackageImportTest {
    
    
	public static void main(String[] args) {
    
    
		
		String info = Arrays.toString(new int[]{
    
    1,2,3});
		
		Bank bank = new Bank();
		
		ArrayList list = new ArrayList();
		HashMap map = new HashMap();
		
		Scanner s = null;
		
		System.out.println("hello!");
		
		Person p = new Person();
		
		Account acct = new Account(1000);
		//全类名的方式显示
		com.atguigu.exer3.Account acct1 = new com.atguigu.exer3.Account(1000,2000,0.0123);
		
		Date date = new Date();
		java.sql.Date date1 = new java.sql.Date(5243523532535L);
		
		Dog dog = new Dog();
		
		Field field = null;
		
		out.println("hello");
		
		long num = round(123.434);
	}
}

2.6 Inheritance

2.6.1 Concept

Inheritance is one of the most significant features of object-oriented programming.

Inheritance is the derivation of a new class from an existing class. The new class can absorb the data attributes and behaviors of the existing class, and can expand new capabilities. (between classes)

Java inheritance is a technology that uses the definition of an existing class as a basis to create a new class. The definition of a new class can add new data or new functions, or use the functions of the parent class, but it cannot selectively inherit the parent class/super class. class/base class. (Subclasses are also called derived classes)

Advantages : This technology makes it very easy to reuse previous code, which can greatly shorten the development cycle and reduce development costs.

example:

// A: 子类         C:父类
class A extends c{
    
      //原来的eat()拿走了  
 }//注意:继承的语法,第二个类不需要再使用class
 
class B extends c{
    
      //原来的eat()拿走了 
 }
 
class c{
    
    
	public void eat(){
    
    
		syso("eat");
	}
}

2.6.2 Features

  1. useextendsKeywords
  2. It is equivalent to a subclass copying the functions of the parent class (including variables and methods. Private resources can also be inherited. However, due to the influence of encapsulation, the subclass cannot be called directly , nor can it be changed by creating an object. It can only be passed through Public methods indirectly call private resources.)
  3. Once subclass A inherits parent class B, subclass A obtains the information declared in parent class B.All properties and methods. In particular, for attributes or methods declared as private in the parent class , after the subclass inherits the parent class, it is still considered to have acquired the private structure in the parent class. Only because of the influence of encapsulation, subclasses cannot directly call the private structure of the parent class.
  4. Java only supports single inheritance (a super class can have multiple derived classes, and a derived class can only inherit from one super class)
  5. Inheritance can be passed on (relationship between grandfather, son and grandson)
  6. After the subclass inherits the parent class, it obtains the properties and methods declared in the direct parent class and all indirect parent classes.
  7. Cannot inherit private members of parent class
  8. Inheritance is mostly used to modify functions. Subclasses can have the functions of the parent class and expand their functions at the same time.
  9. It is the relationship of is a
  10. Java stipulates that the superclass must be constructed before constructing the derived class (first the father and then the son)
  11. Constructor cannot be inherited

2.6.3 Object class understanding

  1. If we do not explicitly declare the parent class of a class, this class inherits from the java.lang.Object class
  2. All java classes (except java.lang.Object class) directly or indirectly inherit from java.lang.Object class
  3. This means that all java classes have the functions declared by the java.lang.Object class.
  4. Because the Object class belongs to the lang package, there is no need to import the package.

2.6.4 Getting Started Case

package cn.tedu.extendsdemo;
 
//测试继承的入门案例
public class Test4_Extends {
    
    
       public static void main(String[] args) {
    
    
              //创建父类对象测试,提高代码的复用性/高内聚,父类写子类的共性
              Father f = new Father();
              f.eat();
//           System.out.println(f.sum);
             
              //创建子类对象测试
              Son s = new Son();
              //5,子类可以使用父类的所有功能,除了private的
              s.eat();
//           System.out.println(s.sum);
             
              //6,继承具有传递性,爷爷的功能,孙子类里也能用
              s.game();
              System.out.println(s.count);
             
       }
}
class Yeye{
    
     //没有指明默认继承Lang包下的Object类
       int count ;
       public void game() {
    
    
              System.out.println("下象棋");
       }



}
//创建父类
//!!耦合性 --继承就是一种强耦合性!!!程序中耦合性越低越好,降低程序的耦合性。  888888888888888888888888(后续用接口)
class Father extends Yeye{
    
    
       //4,如果父类中,资源被private修饰,这个资源子类无法继承
       private int sum =10;
       public void eat() {
    
    
              System.out.println("爸爸在吃猪肉");
       }
}
//创建子类
//1,用extends关键字表示继承关系
//3,Java只支持单继承,一个子类只能继承于一个父类
class Son extends Father{
    
    
//2,继承后,子类就能使用父类的功能,就相当于子类把父类的功能复制了一份
}  //继承不会改变源码,而是拓展

2.6.5 Test: Private property methods can also be inherited

package com.cn.extend;

public class Test {
    
    

	public static void main(String[] args) {
    
    
		Student stu = new Student();
		stu.setAge(15);//吃饭
		stu.eat();//睡觉
		/* 说明:此时使用的对象是子类student,通过公共的方法调用私有的资源,
		 * 而私有资源定义在父类person中,那么此时在子类中必定继承了私有资源
		 * 只不过这些私有的资源由于封装性无法直接使用
		 * 
		 */
		

	}

}


 class Person {
    
    
	
	String name;
	private int age;
	
	public void eat(){
    
    
		System.out.println("吃饭");
		sleep();
	}
	
	private void sleep(){
    
    
		System.out.println("睡觉");
	}
	
	

	public int getAge() {
    
    
		return age;
	}

	public void setAge(int age) {
    
    
		this.age = age;
	}
	
	
}
 
 
class Student extends Person{
    
    
		
	private String name = "小明";
		
}

2.6.6 Use of member variables

package cn.tedu.extendsdemo; 
//测试继承中成员变量的用法
//可以使用从父类中继承过来的,也可以用自己特有的
public class Test5_UseExtends {
    
    
    public static void main(String[] args) {
    
    
       //TODO 创建子类对象测试
       Erzi zi = new Erzi();
       System.out.println(zi.count);//20
       System.out.println(zi.sum);
    }
}
//创建父类
class BaBa{
    
    
    int count = 10;
}
 
//创建子类
class Erzi extends BaBa{
    
    
    int count = 20;
    int sum = 20;
}

2.6.7 Use of member methods

package cn.tedu.extendsdemo;
//测试继承中成员方法的用法
public class Test5_UseExtends {
    
    
       public static void main(String[] args) {
    
    
              //TODO 创建子类对象测试
              Erzi zi = new Erzi();
              //可以使用父类的功能,也可以使用自己特有的功能
              System.out.println(zi.count);//20
              System.out.println(zi.sum);
             
              //2,如果子类没有发生方法重写,eat()使用父类的功能。
              //如果子类发生了方法重写,使用的就是重写之后,也就是子类的eat()的功能。888888888888
              zi.eat();//爸爸在吃肉  --》儿子在喝汤
              zi.code();//可以使用特有的方法
       }
}
//创建父类
class BaBa{
    
    
       int count = 10;
      
       public void eat() {
    
    
              System.out.println("爸爸在吃肉");
       }
}
//创建子类
class Erzi extends BaBa{
    
    
       int count = 20;
       int sum = 20;
      
       //1,方法重写:出现的原因是:当父类的功能需要修改时,我们不能直接打开父类代码修改源码!!我可只能功能扩展
       //扩展的过程:先发生继承关系,然后发生方法重写的现象。要求子类的方法声明和父类一模一样。
       public void eat() {
    
    
System.out.println(count);//20
              System.out.println(super.count);//10,通过super调用父类的功能
              System.out.println("儿子在喝汤");
       }
      
       //提供子类特有方法
       public void code() {
    
    
              System.out.println("儿子在敲代码");
       }
      
}

2.6.8 Use of constructors (constructors cannot be inherited)

1. When a subclass creates an object, it will access the parameterless constructor of the parent class by default.
2. In the first line of the constructor method, there is a default statement: super();
3. When the parent class does not have a parameterless constructor, You can use super to call other constructs of the parent class

package cn.tedu.extendsdemo;
//测试继承中构造方法的使用
public class Test6_UseExtends2 {
    
    
       public static void main(String[] args) {
    
    
              //TODO 创建子类对象测试
              Zi zi = new Zi();
             
       }
}
//创建父类
class Fu{
    
    
       //如果父类中,只提供含参构造,这时,无参构造就会被覆盖,没了!
//建议提供一个无参构造。
       public Fu(String n) {
    
    
              System.out.println("Fu()...");
       }
}
//创建子类
class Zi extends Fu{
    
    
      
       public Zi() {
    
    
              //0,super关键字常用于子类中,当子类要使用父类功能时,通过super代表父类对象的引用。
              //1,子类创建对象时,默认就会存在super(),也就默认就会去访问父类的无参构造。
//           super();//父类没有无参构造了!!
              //2,当父类中不提供无参构造时,只能通过super调用父类的含参构造
              //3,super关键字如果在构造方法中使用,必须是第一条语句。
              super("tony");
              System.out.println("Zi()...");
       }
      
}

2.7 super keyword

Note:
1. The content of the parent class can be used through the super keyword.
2. Super represents a reference object of the parent class
. 3. If used in the constructor, it must be the first statement.

grammar:

1)super.成员变量名------访问超类的成员变量(用于:子父类定义同名的变量,想要在子类中使用父类的变量时使用。父子类定义2个相同名字的变量不会覆盖,变量没有覆盖功能。)
2)super.方法名()-------调用超类的方法(用于:当子类重写了父类中的方法以后,我们想在子类的方法中调用父类中被重写的方法时,则必须显式的使用"super.方法"的方式,表明调用的是父类中被重写的方法。)
3)super()--------------调用超类的构造方法

Question :Why is the constructor of the parent class first called when instantiating an object of a subclass?

Answer: Because after the subclass inherits the parent class, it obtains the content (properties/fields) of the parent class, and these contents must be initialized before use, so the constructor of the parent class must be called first to initialize the content.

Notice:

  1. super can only appear in subclass methods or constructors.
  2. There can only be one super in a subclass constructor.
  3. When super calls the constructor of the parent class in the constructor of the subclass, it must be located on the first line of the constructor of the subclass. (There is no such requirement in the ordinary method)
  4. Even if you don't write it, it defaults to the first line in the subclass constructor to call the parent class's parameterless constructor. If the parent class overloads the class constructor, its subclass super needs to be called according to the different parameters passed.
  5. In the constructor of a subclass, you can call the constructor of the parent class, or you can call the ordinary method of the parent class. Ordinary methods in subclasses can only call ordinary methods of the parent class, but not constructor methods.

2.7.1 The whole process of instantiation of subclass objects

Insert image description here

The whole process of instantiation of subclass objects :

  1. Judging from the results : (Inheritance)
    After the subclass inherits the parent class, it obtains the attributes or methods declared in the parent class.
    When an object of a subclass is created, all attributes declared in the parent class will be loaded in the heap space.

  2. From a process point of view :
    when we create a subclass object through the subclass's constructor, we will definitely call the constructor of its parent class directly or indirectly, and then call the constructor of the parent class's parent class,... until java is
    called Until the constructor with empty parameters in the .lang.Object class. It is precisely because all the structures of the parent class have been loaded that we can see that there are structures in the parent class in the memory, and only then can the subclass object be considered for calling.

Clarity : Although the constructor of the parent class is called when creating a subclass object, an object has been created from beginning to end, which is the new subclass object.

2.8 The difference between this and super

The objects represented are different

  1. this: represents a reference to an object of this class.
  2. super: represents a reference to the parent class object.

premise:
3. this: can be used without inheritance.
4. super: can only be used under inheritance conditions.

When calling the constructor:
5. this: The structure of this class
6. super: The structure of the parent class

Note : this and super cannot appear in the same constructor at the same time. As long as they appear, they must be placed in the first line of the constructor. If they appear at the same time, which one should be placed in the first line?

2.9 Rewriting of methods

Prerequisite :Occurs in parent-child classes

Follow the principle of two same, two small and one big :

两同:方法名相同,参数列表相同(注意:参数列表的相同不相同只和形参类型有关,和形参名字没有关系。)
两小:
  1: 子类的返回值类型小于或等于父类的
    1.1void和基本类型时,必须相同
    1.2引用类型时:小于或等于父类的
  2:子类抛出的异常小于或等于父类的
一大:子类的访问权限大于或等于父类的

Note :

  1. Overriding refers to the rewriting of methods, and attributes have no overriding function (Overloading too)。
  2. The overridden method body can also be the same, which is similar to overloading but has no meaning, and is generally different.
  3. Private methods in parent classes cannot be overridden because private methods cannot be inherited.
  4. The static method cannot be overridden and belongs to the class, it does not belong to the instance.
  5. Methods with the same name and parameters in the subclass and parent class must either be declared as non-static (consider overriding), or both must be declared static (not overridden).
  6. Final modified methods cannot be overridden.
  7. Constructors cannot be overridden.
  8. The overridden method is marked with the @Override annotation: it has a specific small function, which indicates that this method overrides the function of the parent class.

Why a rewrite? ? ?
When the functions of the parent class are not required or not necessarily satisfied by the subclass, they need to be rewritten.

2.9.1 Rewriting the Getting Started Case

package cn.tedu.extendsdemo;
//测试继承中成员方法的用法
public class Test5_UseExtends {
    
    
       public static void main(String[] args) {
    
    
              //TODO 创建子类对象测试
              Erzi zi = new Erzi();
              //可以使用父类的功能,也可以使用自己特有的功能
              System.out.println(zi.count);//20
              System.out.println(zi.sum);
             
              //2,如果子类没有发生方法重写,eat()使用父类的功能。
              //如果子类发生了方法重写,使用的就是重写之后,也就是子类的eat()的功能。888888888888
              zi.eat();//爸爸在吃肉  --》儿子在喝汤
              zi.code();//可以使用特有的方法
       }
}
//创建父类
class BaBa{
    
    
       int count = 10;
      
       public void eat() {
    
    
              System.out.println("爸爸在吃肉");
       }
}
//创建子类
class Erzi extends BaBa{
    
    
       int count = 20;
       int sum = 20;
      
       //1,方法重写:出现的原因是:当父类的功能需要修改时,我们不能直接打开父类代码修改源码!!我可只能功能扩展
       //扩展的过程:先发生继承关系,然后发生方法重写的现象。要求子类的方法声明和父类一模一样。
       public void eat() {
    
    
System.out.println(count);//20
              System.out.println(super.count);//10,通过super调用父类的功能
              System.out.println("儿子在喝汤");
       }
      
       //提供子类特有方法
       public void code() {
    
    
              System.out.println("儿子在敲代码");
       }
      
}

2.10 Expansion

2.10.1 The difference between rewriting and overloading (the difference between Overload and Override)

1. Overloading: means that multiple methods in the same class have the same name, but these methods have different parameter lists, that is, the number or parameter types of parameters cannot be exactly the same. 2. Overriding: there are sub- and parent classes
. Intermediately, the method defined by the subclass has the same method name, the same parameter list and the same return type as the method in the parent class. 3.
Rewriting is a manifestation of polymorphism between the parent class and the subclass
. 4. Overloading is a manifestation of polymorphism in a class

2.10.2 Inherited memory structure

Insert image description here

3 Day08 – Object Oriented 3

3.1 static

3.1.1 Concept

1. It is a keyword in Java
. 2. It is used to modify members ( member variables and member methods, static code blocks ). It cannot modify local resources and constructors.

3.1.2 Features

1. You can modify member variables, member methods, and static code blocks. Classes cannot be modified, except for static inner classes.
2. Loaded as the class is loaded, prior to object loading
3. Loaded only once, it will always exist, no new space will be opened
4. Globally unique, globally shared
5. Can be called directly by class name ( static resources can be used) Called through class name point )
6.Static methods cannot be overridden

Note :静态属性、静态方法和私有的属性都可以被继承和隐藏而不能被重写,因此不能实现多态,不能实现父类的引用可以指向不同子类的对象。非静态方法可以被继承和重写,因此可以实现多态。静态方法和属性是属于类的,调用的时候直接通过类名.方法名完成调用,不需要继承即可调用 。

Question: Static can only call static, non-static can call both static and non-static, why?
Because : static resources are loaded as the class is loaded, taking precedence over object loading. The object has not been created when the class loading is completed, so it cannot be called.
In the same way, static cannot be shared with this or super : this and super replace objects. When there is static, there may not be an object. The main method is also a static method, so this and super are not written.

Summary of the calling relationship :
Calls between the same class do not need to create objects, and resource calls between different classes create objects or use static resources.
non-static resources (Instance variables and ordinary methods, excluding local variables, because if you want to call local variables, you must first call the method) can only be used by creating objects, static resources (Static variables and static methods) can be created by creating an object or by calling the class name directly (It is recommended to use class name to call static resources.)。

3.1.3 Getting Started Case


package cn.tedu.staticdemo;
 //static一般放在返回值类型之前。 
//这个类用来测试静态入门案例
public class Test1_Static {
    
    
       public static void main(String[] args) {
    
    

 //2,静态资源优先于对象加载,会优先加载进内存
//静态资源访问:有2种。
//1:通过new对象进行访问·(但是不推荐用)
//2:直接通过类名.访问
//非静态资源只能有一种:通过对象
              Person.game();
              System.out.println(Person.age);
             
              //TODO 创建Person对象测试
              Person p = new Person();
              p.eat();
              System.out.println(p.name);
             //1.1,   静态资源,可以通过对象访问
             p.game();
              System.out.println(p.age);
             
             //1, 静态资源,还可以通过类名访问
              Person.game();
              System.out.println(Person.age);
             
             
              //3,静态资源,在多个对象间,是共享的

              Person p1 = new Person();
              Person p2 = new Person();
              p1.age=10;
             System.out.println(p2.age);//10
             
       }
}
 
//创建Person类
class Person{
    
    
      
       //普通资源
       String name;
       public void eat() {
    
    
              System.out.println("eat()...");
       }
      
       //静态资源 -- 使用static修饰
       static int age;
       static public void game () {
    
    
             System.out.println("game()...");
       }
      
}

3.1.4 Comprehensive case

package com.atguigu.java1;
/*
 * static关键字的使用
 * 
 * 1.static:静态的
 * 2.static可以用来修饰:属性、方法、代码块、内部类
 * 
 * 3.使用static修饰属性:静态变量(或类变量)
 * 		3.1 属性,按是否使用static修饰,又分为:静态属性  vs 非静态属性(实例变量)
 * 		   实例变量:我们创建了类的多个对象,每个对象都独立的拥有一套类中的非静态属性。当修改其中一个对象中的
 *              非静态属性时,不会导致其他对象中同样的属性值的修改。
 *       静态变量:我们创建了类的多个对象,多个对象共享同一个静态变量。当通过某一个对象修改静态变量时,会导致
 *              其他对象调用此静态变量时,是修改过了的。
 * 		3.2 static修饰属性的其他说明:
 * 			① 静态变量随着类的加载而加载。可以通过"类.静态变量"的方式进行调用
 *          ② 静态变量的加载要早于对象的创建。
 *          ③ 由于类只会加载一次,则静态变量在内存中也只会存在一份:存在方法区的静态域中。
 *          
 *          ④		类变量	实例变量
 *          类		yes		no
 *          对象		yes		yes
 *          
 *      3.3 静态属性举例:System.out; Math.PI;
 * 
 * 4.使用static修饰方法:静态方法
 * 		① 随着类的加载而加载,可以通过"类.静态方法"的方式进行调用
 * 		②			静态方法	非静态方法
 *          类		yes		no
 *          对象		yes		yes
 * 		③ 静态方法中,只能调用静态的方法或属性
 *        非静态方法中,既可以调用非静态的方法或属性,也可以调用静态的方法或属性
 * 
 * 5. static注意点:
 *    5.1 在静态的方法内,不能使用this关键字、super关键字
 *    5.2 关于静态属性和静态方法的使用,大家都从生命周期的角度去理解。
 *    
 * 6. 开发中,如何确定一个属性是否要声明为static的?
 * 		> 属性是可以被多个对象所共享的,不会随着对象的不同而不同的。
 * 		> 类中的常量也常常声明为static
 * 
 *    开发中,如何确定一个方法是否要声明为static的?
 *    	> 操作静态属性的方法,通常设置为static的
 *      > 工具类中的方法,习惯上声明为static的。 比如:Math、Arrays、Collections
 */
public class StaticTest {
    
    
	public static void main(String[] args) {
    
    
		
		Chinese.nation = "中国";
		
		
		Chinese c1 = new Chinese();
		c1.name = "姚明";
		c1.age = 40;
		c1.nation = "CHN";
		
		Chinese c2 = new Chinese();
		c2.name = "马龙";
		c2.age = 30;
		c2.nation = "CHINA";
		
		System.out.println(c1.nation);
		
		//编译不通过
//		Chinese.name = "张继科";
		
		
		c1.eat();
		
		Chinese.show();
		//编译不通过
//		Chinese.eat();
//		Chinese.info();
	}
}
//中国人
class Chinese{
    
    
	
	String name;
	int age;
	static String nation;
	
	
	public void eat(){
    
    
		System.out.println("中国人吃中餐");
		//调用非静态结构
		this.info();
		System.out.println("name :" +name);
		//调用静态结构
		walk();
		System.out.println("nation : " + nation);
	}
	
	public static void show(){
    
    
		System.out.println("我是一个中国人!");
		//不能调用非静态的结构
//		eat();
//		name = "Tom";
		//可以调用静态的结构
		System.out.println(Chinese.nation);
		walk();
	}
	
	public void info(){
    
    
		System.out.println("name :" + name +",age : " + age);
	}
	
	public static void walk(){
    
    
		
	}
}

3.1.5 Static method memory map

Insert image description here

Memory: managed by JVM
1. Heap: all new objects (including new objects and member variables)
2. Stack: local variables (including the address of the numeric reference type of the basic type of the method parameter)
3. Method area: .class bytecode file, static method area, constant pool.

3.2 Static code block

3.2.1 Overview

1. Static code block: loaded when the class is loaded, and only loaded (transfer) once, generally used for project initialization.
2. Location: outside the method in the class

3.2.2 Features

  1. There can be output statements inside
  2. Executed as the class is loaded, and only executed once
  3. Function: Initialize class information
  4. If multiple static code blocks are defined in a class, they will be executed in the order of declaration.
  5. The execution of static code blocks takes precedence over the execution of non-static code blocks.
  6. Only static properties and static methods can be called within a static code block, and non-static structures cannot be called.

Syntax :

static{
    
    
}

3.2.3 Test static, structural, and local code block loading order

The execution order is: Static code block is the fastest, because it is automatically called when the class is loaded, and is only called once, followed by construction code block, construction method, and local code.

package cn.tedu.block;

//测试代码块
 

//总结:
//1, 触发时间节点:调用方法时,会先进入类里面,然后会自动调用静态块(即,类被第一次加载时)
//2,位置 :类里面,方法外     
//3,作用/功能:只被加载一次的时候用。
//执行顺序是:静态代码块最快,因为它是类加载的时候被自动调用,且只调用一次其次是构造代码块,构造方法,局部代码快。
public class Test3_Block {
    
    
    public static void main(String[] args) {
    
    
      //TODO 创建对象测试
       TestBlock tb = new TestBlock();
       tb.show();//触发局部代码块
      
       TestBlock tb2 = new TestBlock();
       
    }
}
//创建TestBlock类
class TestBlock{
    
    
    //1,提供构造代码块
   {
    
    
       System.out.println("构造代码块");
    }
   
    //2,提供静态代码块:加载的早,而且只加载一次
    static{
    
    
      System.out.println("静态代码块");
    }
   
    //3,提供构造方法
    public TestBlock() {
    
    
       System.out.println("构造方法");
    }
   
    //4,提供局部代码块
    public void show() {
    
    
       {
    
    
           System.out.println("局部代码块");
       }
    }
}

3.2.4 Summary: static code blocks, constructed code blocks, local code blocks

Static code block static{ }: It is loaded when the class is loaded and is only loaded once . It is generally used for project initialization.Outside of methods in class

Construction code block { }: It will be called automatically when creating an object. It will be called every time an object is created. It is usually used to extract the common code in the construction method. It can initialize the properties of the object when creating the object.Outside of methods in class

Local code block { }: called when calling a method, used to control the scope of variables.in method

3.2.5 Extension: The difference between static code blocks and static methods

  1. If some code must be executed when the project is started, you need to use static code blocks, which are actively executed;
  2. If you need to initialize when the project starts, without creating an object, you need to use a static method when called by other programs. This kind of code is passively executed. Static methods are loaded when the class is loaded and can be called directly using the class name. For example: the main method must be static, which is the program entry point.

The difference between the two :Static code blocks are executed automatically, and static methods are executed when called.

3.2.6 The final chapter on member variable assignment

package com.atguigu.java3;
/*
 * 对属性可以赋值的位置:
 * ①默认初始化
 * ②显式初始化/⑤在代码块中赋值(② ⑤谁在前谁在后,和定义的顺序有关)
 * ③构造器中初始化
 * ④有了对象以后,可以通过"对象.属性"或"对象.方法"的方式,进行赋值
 * 
 * 
 * 执行的先后顺序:① - ② / ⑤ - ③ - ④
 */


public class OrderTest {
    
    
	public static void main(String[] args) {
    
    
		Order order = new Order();
		System.out.println(order.orderId);
	}
}

class Order{
    
    
	
	
	int orderId = 3;
	{
    
    
		orderId = 4; //最终输出为4
	}
	//还可以写成:相当于定义了2个变量顺序无所谓
	{
    
    
		orderId = 4;
	}
	int orderId = 3;//输出为3
}

3.3 final

3.3.1 Concept

  1. is a keyword provided by java.
  2. final means final.
  3. Final can modify classes, methods, variables, and member locals.

The original intention is because :After inheritance appears in Java, subclasses can change the functions of the parent class. When the functions of the parent class do not allow the subclass to change, the final keyword can be used to modify the parent class.

3.3.2 Features

  1. Classes modified by final cannot be inherited (Benefits: The significance of making a class non-inheritable is that it can protect the class from being modified by inheritance and control the harm caused to the system by abusing inheritance). Such as: String class, System class, StringBuffer class.

  2. Methods modified by final cannot be overridden, but they can be overloaded. For example: getClass(); in Object class;

  3. A variable modified by final is a constant and its value cannot be changed.
    Final modified attributes (member variables) : The locations that can be considered for assignment are: explicit initialization, initialization in code blocks, and initialization in constructors (assignment cannot be done through common objects, because the object will not appear until the constructor method is executed, and it will be in the heap There is already a default initialized value. At this time, assigning a value is equivalent to modifying a constant, and a constant cannot be modified)

    Final modified local variables : Especially when final is used to modify a formal parameter, it indicates that the formal parameter is a constant. When we call this method, assign an actual parameter to the constant parameter. Once assigned, this formal parameter can only be used within the method body, but cannot be reassigned.

Note : When final modifies a reference type variable, it means that the reference cannot be changed, but the properties of the object can be changed at will.

The definition form of constants : final 数据类型 常量名 = 值;, generally in order to facilitate external calls, they will be modified by static and can be directly accessed by the class name. The final form is a global constant : static final 数据类型 常量名 = 值;.

Constant naming convention :It is recommended that all letters in constant names be capitalized, and multiple words separated by underscores ("_") (recommended but not mandatory)
Notes on constants:

  1. It must be declared to be initialized at the same time ( the initial value must be assigned directly and cannot be modified ), (assignment in a static block is also possible, but not recommended)
  2. Accessed by class name point and cannot be changed

Advantages of constants : Constants are directly replaced with specific values ​​at compile time - high efficiency

When are constants used ? Data never changes and is used frequently.

3.3.3 Getting Started Case

package com.atguigu.java3;
/*
 * final:最终的
 * 
 * 1. final可以用来修饰的结构:类、方法、变量
 * 
 * 2. final 用来修饰一个类:此类不能被其他类所继承。
 *          比如:String类、System类、StringBuffer类
 * 
 * 3. final 用来修饰方法:表明此方法不可以被重写
 * 			比如:Object类中getClass();
 * 
 * 4. final 用来修饰变量:此时的"变量"就称为是一个常量
 * 	    4.1 final修饰属性:可以考虑赋值的位置有:显式初始化、代码块中初始化、构造器中初始化
 * 		4.2 final修饰局部变量:
 *           尤其是使用final修饰形参时,表明此形参是一个常量。当我们调用此方法时,给常量形参赋一个实参。一旦赋值
 *           以后,就只能在方法体内使用此形参,但不能进行重新赋值。
 *           
 *  static final 用来修饰属性:全局常量
 */
public class FinalTest {
    
    
	
	final int WIDTH = 0;
	final int LEFT;
	final int RIGHT;
//	final int DOWN;
	
	{
    
    
		LEFT = 1;
	}
	
	public FinalTest(){
    
    
		RIGHT = 2;//多个构造器都要赋值否则报错
	}
	
	public FinalTest(int n){
    
    
		RIGHT = n;
	}
	
//	public void setDown(int down){
    
    
//		this.DOWN = down;
//	}
	
	
	public void doWidth(){
    
    
//		width = 20;
	}
	
	
	public void show(){
    
    
		final int NUM = 10;//常量
//		NUM += 20;
	}
	
	public void show(final int num){
    
    
//		num = 20;//编译不通过
		System.out.println(num);
	}
	
	
	public static void main(String[] args) {
    
    
		
		int num = 10;
		
		num = num + 5;
		
		FinalTest test = new FinalTest();
//		test.setDown(3);
		
		test.show(10);
	}
}


final class FinalA{
    
    
	
}

//class B extends FinalA{
    
    
//	
//}

//class C extends String{
    
    
//	
//}

class AA{
    
    
	public final void show(){
    
    
		
	}
}

class BB extends AA{
    
    
	
//	public void show(){
    
    
//		
//	}
}

3.4 Polymorphism

3.4.1 Concept

Polymorphism refers to the same entity having multiple forms at the same time. It is an important feature of object-oriented programming (OOP). It mainly refers to the same object representing different objects at different times, and refers to the multiple forms of the object.

Object polymorphism : The parent class reference points to the child class object (or the reference of the child class object assigned to the parent class).
Example 1:

// 可以指向不同的子类对象,体现多态性
Animal a = new Dog();
//父类         子类
Animal a = new Cat();

Example 2:
Water can have multiple forms at different times, including water vapor, ice, and water.
How does Java embody polymorphism? Dogs come in two forms: dogs and small animals

class Animal {
    
    
    public void eat(){
    
    
     
    }
}
class Dog extends Animal{
    
    
}
class Test1{
    
    
    main(){
    
    
       //创建子类对象测
       Dog d = new Dog();//小狗就是小狗
      
       //创建多态对象测试
       Animal a = new Dog();//小狗是小动物(是父类类型就是多态)
      
       //父类引用 ,指向  子类对象
      
      //编译ctrl+s看左边,运行ctrl+f11看右边
      
    }
}

3.4.2 Features

1. Premise of polymorphism 1 : Two classes have an inheritance relationship
2. Premise of polymorphism 2 : There must be method overriding
3. Polymorphism refers to the polymorphism of methods, and there is no polymorphism in attributes (because there is no overriding of attributes) Write).
4. Attributes: The attributes of the parent class are called.
5. Method: The method statement of the parent class is called, and the output is the method body of the subclass that overrides the parent class method (except static methods) 6. Static
method: can be inherited and hidden but cannot be overridden, so it cannot implement multiple methods state.
7. The parent class reference points to the subclass object, such as: Animal a = new Dog(); - large type to small type , also called upward transformation
8. pereson p = new Son();What can be called is always related to the left side of the equal sign and has nothing to do with the right side.
9. In polymorphism, look at the left side for compilation ( look at the left side for what can be called ), and look at the right side for operation (look at the right side for what can be output).
The code we write is a .java source file. Ctrl + s will automatically compile the .java file into a .class Bytecode file.
Insert image description here

3.4.3 Getting Started Case

package cn.tedu.duotai;
 
//测试多态的入门案例
public class Test5_Duotai {
    
    
    public static void main(String[] args) {
    
    
       //TODO 创建父类对象测试
       Animal a = new Animal();
       a.eat();//就是使用父类自己的功能
      
       //TODO 创建子类对象测试
       Dog d = new Dog();
       d.eat();//重写前,用父类的。重写后,执行的就是子类的。
      
       //TODO 创建多态对象测试
       Animal an = new Dog();//口诀1:父类引用 指向 子类对象
       //口诀2:编译看左边,运行看右边
       //编译看左边:想要能够保存成功,只能使用左边也就是父类提供的方法声明部分
       //运行看右边:是指发生了重写后,执行结果以子类为准
       an.eat();//调用了父类的方法声明,输出的是子类的重写父类方法的方法体。   888888888888888
      
       //多态主要用来统一调用标准:所有方法的调用向父类看齐
      
    }
   
}
//1, 多态的前提:继承+重写
//创建父类
class Animal{
    
    
    public void eat() {
    
    
       System.out.println("爸爸在吃肉");
    }
}
//创建子类
class Dog extends Animal{
    
    
    @Override   //它会检查是否写了方法重写,2者一块出现
    public void eat() {
    
    
       System.out.println("儿子在喝汤");
    }
//子类特有方法,多态对象不能调用!!!!想用,可以创建子类对象用
    public void eat2() {
    
    
       System.out.println("儿子在喝汤");
    }
}

3.5 Benefits of Polymorphism

  1. Polymorphism allows us to use certain methods of the subclass object without having to care about the specific type of a subclass object and use the parent class to receive it. In this way, universal code can be written and universal programming can be done. (Right now:Unify the calling standard, and the standard is the parent class.)
  2. Improved program scalability and maintainability

3.5.1 Testing: The benefits of polymorphism

package com.cn.extend;


import java.sql.Connection;


//多态性的使用举例一:
public class AnimalTest {
    
    
	
	public static void main(String[] args) {
    
    
		
		AnimalTest test = new AnimalTest();
		test.func(new Dog());
		
		
		test.func(new Cat());
	}
	
	/* 情景:想要使用子类特有的方法。
	 * 有多态 :只需要定义一个方法,方法的参数是父类对象类型,调用时传递不同的子类对象来调用不同子类特有方法。       
	 * 没有多态:需要定义多个重载的方法,每个方法定义对应的子类对象类型,调用时传递不同的子类对象来调用不同子类特有方法。
	 */
	public void func(Animal animal){
    
    //Animal animal = new Dog(); 有多态
		animal.eat();
		animal.shout();
		
		if(animal instanceof Dog){
    
    
			Dog d = (Dog)animal;
			d.watchDoor();
		}
	}
	
//	public void func(Dog dog){  没有多态每次需要定义重载的方法 Dog dog = new Dog();
//		dog.eat();
//		dog.shout();
//	}
//	public void func(Cat cat){  Cat cat = new Cat();
//		cat.eat();
//		cat.shout();
//	}
}


class Animal{
    
    
	
	
	public void eat(){
    
    
		System.out.println("动物:进食");
	}
	
	public void shout(){
    
    
		System.out.println("动物:叫");
	}
	
	
}

class Dog extends Animal{
    
    
	public void eat(){
    
    
		System.out.println("狗吃骨头");
	}
	
	public void shout(){
    
    
		System.out.println("汪!汪!汪!");
	}
	
	public void watchDoor(){
    
    
		System.out.println("看门");
	}
}
class Cat extends Animal{
    
    
	public void eat(){
    
    
		System.out.println("猫吃鱼");
	}
	
	public void shout(){
    
    
		System.out.println("喵!喵!喵!");
	}
}

//举例二:

class Order{
    
    
	
	public void method(Object obj){
    
    //只需要声明一个方法接收它的本身或子类对象类型。
		
	}
}

//举例三:
class Driver{
    
    
	
	/* conn = new MySQlConnection(); conn = new OracleConnection(); 
	 *  比如Connection是操作数据库连接对象Api的统一父类对象类型,通过父类的引用调用方法操作数据库
	 *  的步骤是固定的几步都是调用这几个方法。
	 *  现在连接的是mysql只需要调用方法时传递mysql的连接对象,
	 *  变为连接的是oracle数据库的对象,只需要在调用方法时传递oracle的对象即可,
	 *  连方法中的代码都不用改变(因为多态调用的是父类方法的声明,输出的是子类重写父类方法的方法体)。
	 *  
	 */
	public void doData(Connection conn){
    
    
		//规范的步骤去操作数据
//		conn.method1();
//		conn.method2();
//		conn.method3();
		
	}
	
}

3.6 Type conversion (upward shaping/downward shaping)

Description :

  1. It can only be a reference to the parent class that points to such an object.
  2. Upward styling: automatic conversion
  3. Downcasting: requires forced transfer ( rarely used ), generally used to use subclass-specific resources in polymorphism
  4. In Java, super classes are considered large and derived classes are small.
  5. The forced conversion of basic types in Java will not report an error, but there are only two types of reference type conversions that are successful.
  6. When a subclass is converted into a parent class, some of its original methods may be lost.

For forced type conversion (downward casting), there are only two conditions for success :

  1. The object pointed to by the reference is the type (the object pointed to by the reference refers to the object pointed to by the reference in the upward cast, compared with the one in the brackets of the downward cast.)
  2. The object pointed to by the reference implements the interface or inherits the class

Suggestion : If the above conditions are not met during forced conversion, a ClassCastException type conversion exception will occur. Usually before the forced transfer, instanceof (the result is true or false) is used to determine whether the object pointed to by the reference is of this type.

3.6.1 Downward styling: instance of

Function : Determine whether this object is an instance of this specific class or its subclass.
Example 1

package com.shuai;

public class Demo04 {
    
    
    public static void main(String[] args) {
    
    
        //类型之间的转换:类似于基本类型转换   父(高)  子(低)
        //高                 低
        Person1 person1 = new Student1();//向上造型
        //person1.go();报错,父类里面没有子类特有的方法,无法调用
        //解决:将person1转化为Student1类型,就可以使用了
        Student1 ss = (Student1) person1; //向下造型:想用子类特有的方法。
        ss.go();
        //2句话写成一块:((Student1) person1).go(); 需要多写个括号




    }

}
class Person1{
    
    
    public void run(){
    
    
        System.out.println("输出run方法");
    }

}

class Student1 extends Person1{
    
    
    public void go(){
    
    
        System.out.println("输出go方法");
    }

}

Example 2

package com.cn.ins;

import java.util.Date;


public class PersonTest {
    
    
	public static void main(String[] args) {
    
    
		
		Person p1 = new Person();
		p1.eat();//创建父类对象,调用父类的方法
		
		Man man = new Man();
		man.eat();   //创建子类对象,调用子类的方法
		man.age = 25;
		man.earnMoney();
		
		
		Person p2 = new Man();
		p2.eat(); //多态,属性没有多态调用都是父类,方法调用的是父类方法声明以及子类对应的方法体。
		p2.walk();
		
		//不能调用子类所特有的方法、属性:编译时,p2是Person类型。(多态也只是调用重写后的方法,不是特有的方法)
		p2.name = "Tom";
//		p2.earnMoney();
//		p2.isSmoking = true;
		//有了对象的多态性以后,内存中实际上是加载了子类特有的属性和方法的,但是由于变量声明为父类类型,导致
		//编译时,只能调用父类中声明的属性和方法。子类特有的属性和方法不能调用。
		
		//如何才能调用子类特有的属性和方法?
		/* 1.向下转型:使用强制类型转换符。 
		 * 2.直接创建子类的对象进行调用
		 */
		Man m1 = (Man)p2;
		m1.earnMoney();
		m1.isSmoking = true;
		
		//使用强转时,可能出现ClassCastException的异常。
//		Woman w1 = (Woman)p2;  
//		w1.goShopping();
		
		/*
		 * instanceof关键字的使用
		 * 
		 * 引用实例       类型
		 * a instanceof A:判断对象a是否是类A的实例。如果是,返回true;如果不是,返回false。
		 * 
		 * 
		 *  使用情境:为了避免在向下转型时出现ClassCastException的异常,我们在向下转型之前,先
		 *  进行instanceof的判断,一旦返回true,就进行向下转型。如果返回false,不进行向下转型。
		 *  
		 *  如果 a instanceof A返回true,则 a instanceof B也返回true.
		 *  其中,类B是类A的父类。(a A同一个字母表示是同一个变量类型是他本身的实例,字母B不同为true一定为父类。
		 *  即本身赋值给P2的值就是Man类型)
		 */
		if(p2 instanceof Woman){
    
    
			Woman w1 = (Woman)p2;
			w1.goShopping();
			System.out.println("******Woman******");
		}
		
		if(p2 instanceof Man){
    
    //由Person p2 = new Man();可以看出P2是Man类型类型对象的一个实例
			Man m2 = (Man)p2;
			m2.earnMoney();
			System.out.println("******Man******");
		}
		
		if(p2 instanceof Person){
    
    //是它父类的子类实例也可以
			System.out.println("******Person******");
		}
		if(p2 instanceof Object){
    
    
			System.out.println("******Object******");
		}
		
//		if(p2 instanceof String){
    
    
//			
//		}
		
		//练习:
		//问题一:编译时通过,运行时不通过
		//举例一:
//		Person p3 = new Woman();
//		Man m3 = (Man)p3;
		//举例二:
//		Person p4 = new Person();
//		Man m4 = (Man)p4;

		
		//问题二:编译通过,运行时也通过
//		Object obj = new Woman();
//		Person p = (Person)obj;
		
		//问题三:编译不通过
//		Man m5 = new Woman();
		
//		String str = new Date();
		
//		Object o = new Date();
//		String str1 = (String)o;
		
		
		
	}
}

//class Order{
    
    
//	
//}


class Person {
    
    
	String name;
	int age;
	
	int id = 1001;
	
	public void eat(){
    
    
		System.out.println("人:吃饭");
	}
	
	public void walk(){
    
    
		System.out.println("人:走路");
	}
	
}

class Man extends Person{
    
    
		
		boolean isSmoking;
		
		int id = 1002;
		
		public void earnMoney(){
    
    
			System.out.println("男人负责挣钱养家");
		}
		
		public void eat(){
    
    
			System.out.println("男人多吃肉,长肌肉");
		}
		
		public void walk(){
    
    
			System.out.println("男人霸气的走路");
		}

	}



class Woman extends Person{
    
    
	
	boolean isBeauty;
	
	public void goShopping(){
    
    
		System.out.println("女人喜欢购物");
	}
	
	public void eat(){
    
    
		System.out.println("女人少吃,为了减肥");
	}
	
	public void walk(){
    
    
		System.out.println("女人窈窕的走路");
	}
}


3.7 Usage of main method

3.7.1 Case 1: Testing the function of main method

package com.atguigu.java2;
/*
 * main()方法的使用说明:
 * 1. main()方法作为程序的入口
 * 2. main()方法也是一个普通的静态方法
 * 3. main()方法可以作为我们与控制台交互的方式。(之前:使用Scanner)
 * 
 * 
 * 
 */
public class MainTest {
    
    
	
	
	public static void main(String[] args) {
    
    //入口
		
		Main.main(new String[100]);
		
		MainTest test = new MainTest();
		test.show();
		
	}	
	public void show(){
    
    
		
	}
}


class Main{
    
    
		
	public static void main(String[] args) {
    
    
	
		for(int i = 0;i < args.length;i++){
    
    
			args[i] = "args_" + i;
			System.out.println(args[i]);
		}
		
	}
	
}

3.7.2 Case 2: Interaction with the console

In eclipse:
1. First run the main method to generate a bytecode file
Insert image description here

2. Select Run Configurations
Insert image description here
3. The program you just ran will be automatically located at this time
Insert image description here
4. Add parameters
Insert image description here
5. The running results
Insert image description here
are in the Dos command window:
1. Copy the .java file and remove the package name in the code -> place it in the disk directory
Insert image description here
2. Open the command line window
Insert image description here
3. Enter the parameters to run
Insert image description here

3.8 Expansion

3.8.1 The difference between static variables and instance variables

The difference in syntax definition : the static keyword must be added before static variables, but not before instance variables.

The difference when the program is running : Instance variables belong to the attributes of an object. An instance object must be created before the instance variable in it will be allocated space and this instance variable can be used. Static variables do not belong to an instance object, but to a class, so they are also called class variables. As long as the program loads the bytecode of the class without creating any instance objects, the static variables will be allocated space, and the static variables can be Used, of course it can also be used through objects.

In short ,Instance variables must only be used by creating objects. Static variables can be called directly by creating objects or by class names (static variables are recommended to be called by class names)

4 Day09 – Object Oriented 4

4.1 Access control characters

Used to control the access scope of a , or 类中的成员变量,. 方法( 不能用于局部变量)

modifier kind Bag Same package/different package subcategories Anywhere in the same project
public
protected
default
private
Explanation :
  1. public: public, anywhere in the same project , in any class
  2. protected: protected, this class, the same package class, the same package subclass/different package subclasses. Note that different packages can only be used in subclasses, and the same package can be used as long as it is in the same package.
  3. Default: write nothing, this class, the same package class (class in the same package), but you cannot write default
  4. private: private, this class

Notice

  1. Modifiers like public, protected, default, private, static, final, and abstract do not distinguish the order . For example, the modified method only needs to be in the return value type.
  2. The access modifier of a class can only 默认的be or 是public(there can only be one public-modified class in a .java file, and the class name is the same as the file name)
  3. The access modifiers for members (variables, methods) in the class can be any of the four above.
  4. Get used to general data ( member variables ) privatization ( private ) behavior ( method ) public ( public )).
  5. If it is a parent class in an inheritance relationship, the permissions inside are at least protected, because to use its derived class, you need to call the parent class resources.

4.2 Abstract class

4.2.1 Concept

In Java, you can define a method without a method body, which is specifically implemented by its subclass. The method without a method body is called an abstract method, and the class containing an abstract method is called an abstract class .
An abstract class can be understood as a special class with only method declarations and no method bodies.

official:

//抽象方法,没有方法体,大括号也没有,有一个”;”。
修饰符 abstract 返回值类型 方法名(参数列表);

The meaning of abstract class: you can extract the common features of the code, extend it through subclass inheritance, and improve the efficiency of code development.

Examples: fruits, things. .


 
class A{
    
    
	public void eat(){
    
    //声明一样,可以提取
		syso("eat...B")    }
}
class B{
    
    
	public void eat(){
    
    //声明一样,可以提取
	syso("eat…A")   }
}	
abstract class C{
    
    
	public abstract void eat();
}

4.2.2 Features

  1. Implemented through the java keyword abstract .
  2. You can modify methods or classes .
  3. A class containing abstract methods must be an abstract class, and an abstract class does not necessarily contain abstract methods (because it can be implemented by a subclass).
  4. There can be no abstract methods in an abstract class (implemented by subclasses), there can be abstract methods or ordinary methods, and there must be a constructor method (for subclass instantiation), can have member variables and constants .
  5. If there are abstract methods in a class, the class must be defined as an abstract class.
  6. After a subclass inherits an abstract class, (1) it will either remain an abstract class, or (2) it will 所有override all the abstract methods of the parent class.
  7. Mostly used in polymorphism.
  8. Abstract classes cannot be instantiated by new objects but can be new arrays.

Why does an abstract class have a constructor method :Without that your subclass won't compile because the first statement in any constructor implicitly calls super()

Points to note when using abstract:

  1. Abstract cannot be used to modify: properties, constructors and other structures.
  2. Abstract cannot be used to modify private methods, static methods, final methods, and final classes.

Summary: Situations that cannot occur at the same time :

  1. final and abstract cannot appear at the same time because fianl is fixed and cannot be inherited, and
    abstract is generally not used alone, but is used together with derived classes.
  2. this and super cannot be used together because the constructors are both on the first line
  3. static and this super cannot appear at the same time, because the object has not been created when static is present. (The main method is also a static method, so it cannot have this, super)
    Note: The modifier final static abstract is almost always written before void

4.2.3 Getting Started Case

 package cn.tedu.abstractdemo;
//测试抽象类的入门案例 
public class Test1_Abstract {
    
    
    public static void main(String[] args) {
    
    
       //TODO 创建多态对象测试
       //7,抽象类不能被实例化new 所以我们可以用多态实例它普通子类的对象
//     Animal a = new Dog();
       Animal a = new Cat();
       a.eat();//狗吃肉
    }
}
//创建父类
//3,如果类里有抽象方法,这个必须声明成一个抽象类
abstract class Animal{
    
    
    //1,   父类提供的方法,如果子类要改,改的是方法体,但是要求方法声明不许改!!!(及:不用父类的方法体,甚至要覆盖它,可以不写父类的方法体就是抽象方法)
    //这时,我们能不能只提供方法声明,不提供方法体  -- 可以,此时的方法就没有了方法体,称为抽象方法
    //2,   通过abstract来修饰成抽象的
    abstract public void eat() ;
   
    //4,再提供一个抽象方法 和 普通方法
    abstract public void game();
   
    public void chiji() {
    
    
       System.out.println("正在吃鸡");
    }
}
//创建子类
//5,子类继承抽象后,子类可以把所有抽象方法 全都重写,那就是一个普通子类
class Cat extends Animal{
    
    
    //重写所有抽象方法
// 注解:1,说明发生了方法的重写2.检出这个地方必须会发生重写,只有这个注解不写方法会报错
@Override  //快捷键 @ alt+ /
//也可以直接,重写的方法名+alt+/
    public void eat() {
    
    
       System.out.println("猫吃鱼");
    }
@Override
    public void game() {
    
    
       System.out.println("玩毛线");
    }
}
//6,子类继承抽象后,没有把所有抽象方法 全都重写,那就是一个抽象子类
abstract class Dog extends Animal{
    
    
    //重写抽象方法
    @Override
    public void eat() {
    
    
       System.out.println("狗吃肉");
    }
}

4.3 Usage of abstract classes

4.3.1 Construction method

Abstract classes also have constructors, but they cannot be instantiated themselves.
What is the use of the constructor of an abstract class ?
Generally used to instantiate subclasses. (Because the subclass has super, the parent class constructor is called by default.)

package cn.tedu.abstractdemo;
 
//测试抽象类构造方法的用法
public class Test2_UseAbstract {
    
    
    public static void main(String[] args) {
    
    
       //3,抽象类不能被实例化,那提供构造方法有啥用??--用来创建子类对象。

       //原因是:子类创建对象时,构造方法里默认就会存在super()
//     Animal2 a = new Animal2();
       //TODO  创建多态对象测试
       Animal2 a = new Dog2();
    }
}
//创建父类
abstract class Animal2{
    
    
    //1,可以有构造方法  -- 作用:用来创建对象
    public Animal2() {
    
        //最好手动提供一个无参构造
       System.out.println("Animal2()...");
    }
}
//创建子类
class Dog2 extends Animal2{
    
    
    public Dog2() {
    
    
       super();//2,默认就存在,会自动调用父类的构造方法
       System.out.println("Dog2()...");
    }
}

4.3.2 Member variables and constants of abstract classes

There can be both variables and constants

package cn.tedu.abstractdemo;
 
//测试抽象类的成员变量和常量的用法
public class Test2_UseAbstract {
    
    
    public static void main(String[] args) {
    
    
       //3,抽象类不能被实例化,那提供构造方法有啥用??--用来创建子类对象。88888888888888888
       //原因是:子类创建对象时,构造方法里默认就会存在super()
//     Animal2 a = new Animal2();
       //TODO  创建多态对象测试
       Animal2 a = new Dog2();
       System.out.println(a.sum);//10
       System.out.println(a.NAME);//xiongda
       System.out.println(Animal2.NAME);//xiongda
    }
}
//创建父类
abstract class Animal2{
    
    
   
    //a,抽象类里可以提供成员变量
    int sum = 10;
   
    //b,抽象类里可以提供成员常量
    static final String NAME="xiongda";
   
   
    //1,提供构造方法  -- 作用:用来创建对象
    public Animal2() {
    
    
       System.out.println("Animal2()...");
    }
}
//创建子类
class Dog2 extends Animal2{
    
    
    public Dog2() {
    
    
       super();//2,默认就存在,会自动调用父类的构造方法
       System.out.println("Dog2()...");
    }
}

4.3.3 Member methods of abstract classes

  1. In an abstract class, there can be both ordinary methods and abstract methods.
  2. Can all abstract classes have ordinary methods? – Yes
  3. If all the methods in the abstract class are ordinary methods, why should they be modified into abstract classes? - Do not allow the outside world to new (do not allow the outside world to instantiate objects)
  4. Can there be ordinary methods in abstract classes? – Yes
  5. Can abstract classes be instantiated? – No
  6. An abstract class is a special class, what’s so special about it? – It can contain abstract methods
  7. How to decide whether to provide an ordinary method or an abstract method to an abstract class? – See whether to provide a method body
  8. test:
  	
		package cn.tedu.oop;
		//测试  抽象类  成员方法
		public class Test1_UseAbstract {
    
    
			public static void main(String[] args) {
    
    
				//创建多态对象测试
				Fu fu = new Zi();
				fu.eat();
				fu.sleep();
				fu.game();
			}
		}
		//2, 如果类中包含抽象方法,那么,这个类必须修饰成 抽象类
		//3, 抽象类是一个特殊的类 ,比较灵活. 特殊在 :  抽象类里可以有抽象方法 , 也可以有普通方法 .
		//到底是普通方法还是抽象方法,看你要不要提供方法体了.
		abstract class Fu{
    
    
			//4, 这个方法是最终方法,不能被子类重写!!
			final public void eat() {
    
    
				System.out.println("爸爸在吃肉");
			}
			//1 , sleep被子类继承,并且发生了方法重写,也就是想改父类的方法体.---父类就不提供方法体了,就变成了抽象方法
			abstract public void sleep()  ;
			abstract public void game()  ;
		}
		//5 ,  子类继承抽象类以后,可以 重写所有的抽象方法  , 否则 , 子类就包含着抽象方法是一个抽象子类
		class Zi extends Fu{
    
    
			@Override
			 public void sleep()  {
    
    
				System.out.println("Zi...sleep()");
			}
			@Override
			 public void game() {
    
    
				System.out.println("Zi...game()");
			}
		}

4.4 Anonymous subclasses of abstract classes

package com.cn.per;


/*
 * 抽象类的匿名子类:凡是匿名的作用都是为了省事,只用一次。
 * 匿名子类:不用在创建类继承抽象父类后再重写方法,直接在new对象的同时重写方法,简化了代码。
 * 
 */
public class PersonTest {
    
    
	
	public static void main(String[] args) {
    
    
		
		method(new Student());//普通类的匿名对象
		
		Worker worker = new Worker();
		method1(worker);//普通类的普通对象
		
		method1(new Worker());//普通类的匿名对象
		
		System.out.println("********************");
		
		//创建了一匿名子类的普通对象:p   
		/*
		 * 省略class Worker extends Person{......}, 
		 * 直接创建对象的时候重写抽象父类的抽象方法即可,不用在单独的创建类继承后再重写抽象方法。
		 */
		Person p = new Person(){
    
    //注意:这里是创建了没有名字的子类对象,不是父类的对象Person。person是抽象类也不能够创建对象。

			@Override
			public void eat() {
    
    
				System.out.println("吃东西");
			}

			@Override
			public void breath() {
    
    
				System.out.println("好好呼吸");
			}
			
		};
		
		method1(p);
		System.out.println("********************");
		
		//创建匿名子类的匿名对象
		method1(new Person(){
    
    
			@Override
			public void eat() {
    
    
				System.out.println("吃好吃东西");
			}

			@Override
			public void breath() {
    
    
				System.out.println("好好呼吸新鲜空气");
			}
		});
	} //main方法的结束符
	
	
	public static void method1(Person p){
    
    
		p.eat();
		p.breath();
	}
	
	public static void method(Student s){
    
    
		
	}
}

class Worker extends Person{
    
     //用了匿名子类的对象这一步可省略

	@Override
	public void eat() {
    
    
	}

	@Override
	public void breath() {
    
    
	}
	
}

package com.cn.per;


/*
 * abstract关键字的使用
 * 1.abstract:抽象的
 * 2.abstract可以用来修饰的结构:类、方法
 * 
 * 3. abstract修饰类:抽象类
 * 		> 此类不能实例化
 *      > 抽象类中一定有构造器,便于子类实例化时调用(涉及:子类对象实例化的全过程)
 *      > 开发中,都会提供抽象类的子类,让子类对象实例化,完成相关的操作
 * 
 * 
 * 4. abstract修饰方法:抽象方法
 * 		> 抽象方法只有方法的声明,没有方法体
 * 		> 包含抽象方法的类,一定是一个抽象类。反之,抽象类中可以没有抽象方法的。
 *      > 若子类重写了父类中的所有的抽象方法后,此子类方可实例化
 *        若子类没有重写父类中的所有的抽象方法,则此子类也是一个抽象类,需要使用abstract修饰
 */
public class AbstractTest {
    
    
	public static void main(String[] args) {
    
    
		
		//一旦Person类抽象了,就不可实例化
//		Person p1 = new Person();
//		p1.eat();
		
	}
}

abstract class Creature{
    
    
	public abstract void breath();
}

abstract class Person extends Creature{
    
    
	String name;
	int age;
	
	public Person(){
    
    
		
	}
	public Person(String name,int age){
    
    
		this.name = name;
		this.age = age;
	}
	
	//不是抽象方法:
//	public void eat(){
    
    
//		
//	}
	//抽象方法
	public abstract void eat();
	
	public void walk(){
    
    
		System.out.println("人走路");
	}
	
	
}


class Student extends Person{
    
    
	
	public Student(String name,int age){
    
    
		super(name,age);
	}
	public Student(){
    
    
	}
	
	public void eat(){
    
    
		System.out.println("学生多吃有营养的食物");
	}

	@Override
	public void breath() {
    
    
		System.out.println("学生应该呼吸新鲜的没有雾霾的空气");
	}
}

4.5 Application of abstract classes: design pattern of template method

Insert image description here

package com.atguigu.java;
/*
 * 抽象类的应用:模板方法的设计模式
 * 
 */
public class TemplateTest {
    
    
	public static void main(String[] args) {
    
    
		
		SubTemplate t = new SubTemplate();
		
		t.spendTime();
	}
}

abstract class Template{
    
    
	
	//计算某段代码执行所需要花费的时间
	public void spendTime(){
    
    
		
		long start = System.currentTimeMillis();
		
		this.code();//不确定的部分、易变的部分
		
		long end = System.currentTimeMillis();
		
		System.out.println("花费的时间为:" + (end - start));
		
	}
	
	public abstract void code();
	
	
}

class SubTemplate extends Template{
    
    

	@Override
	public void code() {
    
    
		
		for(int i = 2;i <= 1000;i++){
    
    
			boolean isFlag = true;
			for(int j = 2;j <= Math.sqrt(i);j++){
    
    //开方
				
				if(i % j == 0){
    
    
					isFlag = false;
					break;
				}
			}
			if(isFlag){
    
    
				System.out.println(i);
			}
		}

	}
	
}

4.6 Ways to prevent the outside world from instantiating objects (2 ways)

  1. Modify your class into an abstract class
  2. Make your constructor private

4.7 Ways to assign values ​​to member variables (2 ways)

1. Call setXxx()
2. Use the constructor method to assign values ​​(the constructor method is called when creating an object, and the passed value is assigned to the member variable in the constructor method)

Reason : Not assigning values ​​directly is because the code is hard-coded and inflexible.

5 Day10 – Object Oriented 5

5.1 Interface (default new feature)

5.1.1 Concept

Since multiple inheritance is not allowed in Java, if you want to implement the functions of multiple classes, you can do it by implementing multiple interfaces.
Java 接口and Java 抽象类represent abstract types, which are the specific manifestations of the abstraction layer we need to propose. OOP 面向对象programming,If you want to improve the reuse rate of the program and increase the maintainability and scalability of the program, it must be interface-oriented programming and abstraction-oriented programming., correctly use useful abstract types such as interfaces and abstract classes as the top layer of the Java structure.

grammar:

interface  接口名{
    
     
 代码…  
 }
 
abstract class  类名{
    
     
 代码…
} //2单词变成了一个

5.1.2 Features

  1. The methods in the interface are all public abstract methods, the variables are all public constants, and there are no constructors.( The resources in the interface are all public ).
  2. Create an interface through the interface keyword
  3. Let subclasses implement it through implements (Abstract classes extend inheritance
  4. It can be understood that the interface is a special abstract class
  5. Interface breaks through the limitations of Java's single inheritance
  6. Interfaces and classes can have multiple implementations, interfaces can have multiple inheritances (separated by ","), and inheritance can be multiple implementations at the same time, but it cannot be multiple inheritance and multiple implementations at the same time or changing the order to implement first and then inherit. (Summary: The same type is inheritance, and the difference is implementation relationship.)
  7. Interfaces are rules for external exposure and a set of development specifications.
  8. The interface improves the functional expansion of the program and reduces the coupling (coupling is the correlation of the program, the lower the correlation, the better)

Note :

  1. How to call interface inheritance interface? Because interface is a special abstract class that cannot be instantiated, so we can only create a common subclass to implement this interface and instantiate this implementation class.
  2. pay attentionPermission to override abstract methods in interfaces, because the default is public, the permissions of subclasses are at least equal to public (2 is the same as 2, the smaller is the larger principle).
  3. New default features of interfaces : Starting from jdk 1.8, interfaces can have ordinary methods (static methods and default methods), modified with static or default default (default is not omitted).
  4. The existence of ordinary methods in an interface means : if an abstract class has many abstract methods, it will be too troublesome for subclasses to rewrite them. If you want to rewrite them with ordinary methods, it is convenient to rewrite them.
  5. A subclass inherits an abstract parent class and overrides the methods of the parent class, which is called method rewriting.
    Subclasses implement interfaces and override interface methods, which is called method implementation. Of course, it's okay if you call it rewriting, but it's just not accurate.

5.1.3 Getting Started Case 1

 package cn.tedu.interfacedemo;
//接口的入门案例
public class Test4_Inter {
    
    
    public static void main(String[] args) {
    
    
       //TODO 创建多态对象测试
       //5,接口可以创建对象吗??? --- 不能!!!和抽象类一样,不能实例化
//     Inter i =  new Inter();
       Inter i =  new InterImpl();
       i.delete();
       i.save();
    }
}
//创建接口
//1,通过interface关键字定义接口
interface Inter{
    
    
    //2,接口里可以有普通方法吗???---不可以!!!接口里都是抽象方法
    abstract public void delete();
    abstract public void save();
}
//3,实现类,想要使用接口里的功能,需要 实现  接口,用implements关键字
//4, 实现类实现了接口以后,可以是一个普通实现类,就要求重写所有抽象方法
class InterImpl implements Inter{
    
    
//重写所有抽象方法(注意抽象方法有分号,没有方法体,连{}也没有)
//重写的方法把它变为普通的方法,把abstract去掉,写方法体,注意分号。
    @Override
    public void delete() {
    
    
       System.out.println("delete()...");
    }
    @Override
    public void save() {
    
    
       System.out.println("save()...");
    }
}
//实现类一般都是在接口上加 Impl
//6, 实现类实现了接口以后,如果没有全部重写抽象方法,就是个抽象子类
abstract class InterImpl2 implements Inter{
    
    
}

5.1.4 Getting Started Case 2

package com.atguigu.java1;
/*
 * 接口的使用
 * 1.接口使用interface来定义
 * 2.Java中,接口和类是并列的两个结构
 * 3.如何定义接口:定义接口中的成员
 * 		
 * 		3.1 JDK7及以前:只能定义全局常量和抽象方法
 * 			>全局常量:public static final的.但是书写时,可以省略不写
 * 			>抽象方法:public abstract的
 * 			
 * 		3.2 JDK8:除了定义全局常量和抽象方法之外,还可以定义静态方法、默认方法(略)
 * 
 * 4. 接口中不能定义构造器的!意味着接口不可以实例化
 * 
 * 5. Java开发中,接口通过让类去实现(implements)的方式来使用.
 *    如果实现类覆盖了接口中的所有抽象方法,则此实现类就可以实例化
 *    如果实现类没有覆盖接口中所有的抽象方法,则此实现类仍为一个抽象类
 *    
 * 6. Java类可以实现多个接口   --->弥补了Java单继承性的局限性
 *   格式:class AA extends BB implements CC,DD,EE
 *   
 * 7. 接口与接口之间可以继承,而且可以多继承
 * 
 * *******************************
 * 8. 接口的具体使用,体现多态性
 * 9. 接口,实际上可以看做是一种规范
 * 
 * 面试题:抽象类与接口有哪些异同?
 * 
 */
public class InterfaceTest {
    
    
	public static void main(String[] args) {
    
    
		System.out.println(Flyable.MAX_SPEED);
		System.out.println(Flyable.MIN_SPEED);
//		Flyable.MIN_SPEED = 2;
		
		Plane plane = new Plane();
		plane.fly();
	}
}


interface Flyable{
    
    
	
	//全局常量
	public static final int MAX_SPEED = 7900;//第一宇宙速度
	int MIN_SPEED = 1;//省略了public static final
	
	//抽象方法
	public abstract void fly();
	//省略了public abstract
	void stop();
	
	
	//Interfaces cannot have constructors
//	public Flyable(){
    
    
//		
//	}
}

interface Attackable{
    
    
	
	void attack();
	
}

class Plane implements Flyable{
    
    

	@Override
	public void fly() {
    
    
		System.out.println("通过引擎起飞");
	}

	@Override
	public void stop() {
    
    
		System.out.println("驾驶员减速停止");
	}
	
}

abstract class Kite implements Flyable{
    
    

	@Override
	public void fly() {
    
    
		
	}
	
}

class Bullet extends Object implements Flyable,Attackable,CC{
    
    

	@Override
	public void attack() {
    
    
		// TODO Auto-generated method stub
		
	}

	@Override
	public void fly() {
    
    
		// TODO Auto-generated method stub
		
	}

	@Override
	public void stop() {
    
    
		// TODO Auto-generated method stub
		
	}

	@Override
	public void method1() {
    
    
		// TODO Auto-generated method stub
		
	}

	@Override
	public void method2() {
    
    
		// TODO Auto-generated method stub
		
	}
	
}
//************************************

interface AA{
    
    
	void method1();
}
interface BB{
    
    
	
	void method2();
}

interface CC extends AA,BB{
    
    
	
}

5.1.5 A presentation interface is a canonical and anonymous implementation class object

Anonymous implementation classes of interfaces are used the same as anonymous subclasses of abstract classes.
Insert image description here

package com.atguigu.java1;
/*
 * 接口的使用
 * 1.接口使用上也满足多态性
 * 2.接口,实际上就是定义了一种规范
 * 3.开发中,体会面向接口编程!
 * 
 */
public class USBTest {
    
    
	public static void main(String[] args) {
    
    
		
		Computer com = new Computer();
		//1.创建了接口的非匿名实现类的非匿名对象
		Flash flash = new Flash();
		com.transferData(flash);
		
		//2. 创建了接口的非匿名实现类的匿名对象
		com.transferData(new Printer());
		
		//3. 创建了接口的匿名实现类的非匿名对象
		USB phone = new USB(){
    
    

			@Override
			public void start() {
    
    
				System.out.println("手机开始工作");
			}

			@Override
			public void stop() {
    
    
				System.out.println("手机结束工作");
			}
			
		};
		com.transferData(phone);
		
		
		//4. 创建了接口的匿名实现类的匿名对象
		
		com.transferData(new USB(){
    
    
			@Override
			public void start() {
    
    
				System.out.println("mp3开始工作");
			}

			@Override
			public void stop() {
    
    
				System.out.println("mp3结束工作");
			}
		});
	}
}

class Computer{
    
    
	
	public void transferData(USB usb){
    
    //USB usb = new Flash();
		usb.start();
		
		System.out.println("具体传输数据的细节");
		
		usb.stop();
	}
	
	
}

interface USB{
    
    
	//常量:定义了长、宽、最大最小的传输速度等
	
	void start();
	
	void stop();
	
}

class Flash implements USB{
    
    

	@Override
	public void start() {
    
    
		System.out.println("U盘开启工作");
	}

	@Override
	public void stop() {
    
    
		System.out.println("U盘结束工作");
	}
	
}

class Printer implements USB{
    
    
	@Override
	public void start() {
    
    
		System.out.println("打印机开启工作");
	}

	@Override
	public void stop() {
    
    
		System.out.println("打印机结束工作");
	}
	
}


5.2 Usage of interface

5.2.1 Construction method

There is no constructor method in the interface. When creating an object of the implementation class, the default super() is the parameterless constructor of the default Object called.

public interface Inter2 {
    
    
    //接口里可以有构造方法吗???--没有!!,抽象类有
//  public Inter2() {}
   
   
}

5.2.2 Member variables

  1. The resources in the interface are all public and are modified with public.
  2. Interface variables are static constants by default .
  3. Summary: The variables in the interface are all公共的 静态 常量

example:


public static final  int age;

等价于:

int age; //接口中会默认自动拼接 public static final

5.2.3 Member methods of interfaces

  1. The resources in the interface are all public and are modified with public.
  2. The methods in the interface are abstract by default . Even if they are not written, they will be spliced ​​by default, but they will not be displayed.
  3. Summary: All the methods in the interface 公共的 抽象 方法will be spliced ​​by default even if they are not written, but they will not be displayed.

example:

public abstract void save();

等价于:

void save(); //会默认拼接 public abstract 

5.3 Complex usage of interfaces

The limitations of single inheritance in Java can be solved through interfaces:接口可以多继承也可以多实现,甚至可以继承的同时多实现。

package cn.tedu.interfacedemo;
 
//这个类用来测试接口的复杂用法:多继承多实现
public class Test4_ComInter {
    
    
	public static void main(String[] args) {
    
    
		Interface1 in = new Interface1Impl();
		in.save();
		in.update();
	}
}
//创建接口1
interface Interface1{
    
    
	void save();
	void update();
}
//创建接口2
interface Interface2{
    
    
	void get();
	void delete();
}
//1、打破了java单继承的局限性,因为接口之间可以多继承,多个接口之间逗号隔开
interface Interface3 extends Interface1,Interface2{
    
    
	void add();
}
//3、接口还可以多实现吗??---可以多实现,只不过接口之间逗号隔开
class ManyImpl implements  Interface1,Interface2{
    
    
	public void save() {
    
    }
	public void update() {
    
    }
	public void get() {
    
    }
	public void delete() {
    
    }
}
//4、接口可以继承的同时,多实现?? -- 
class MoreImple extends ManyImpl  implements Interface1,Interface2  {
    
    
}//注意:只能是先继承在多实现。顺序不能变,并且不能多继承多实现。
//2、创建实现类,使用3号接口的功能,需要重写几个方法呢??---同时重写1号和2号和3号接口里的所有功能
class Interface3Impl  implements Interface3{
    
    
	@Override
	public void save() {
    
      }
	@Override
	public void update() {
    
      }
	@Override
	public void get() {
    
      }
	@Override
	public void delete() {
    
    	}
	@Override
	public void add() {
    
    	}
}
//TODO 创建实现类
class Interface1Impl implements Interface1{
    
    
	@Override
	public void save() {
    
    
		System.out.println("save()...");
	}
	@Override
	public void update() {
    
    
		System.out.println("update()...");
	}
}

5.4 Usage of new features of jdk1.8 in the interface

ClassSubClassTest:

package com.atguigu.java8;

public class SubClassTest {
    
    
	
	public static void main(String[] args) {
    
    
		SubClass s = new SubClass();
		
//		s.method1();
//		SubClass.method1();
		//知识点1:接口中定义的静态方法,只能通过接口来调用。
		CompareA.method1();
		//知识点2:通过实现类的对象,可以调用接口中的默认方法。
		//如果实现类重写了接口中的默认方法,调用时,仍然调用的是重写以后的方法
		s.method2();
		//知识点3:如果子类(或实现类)继承的父类和实现的接口中声明了同名同参数的默认方法,
		//那么子类在没有重写此方法的情况下,默认调用的是父类中的同名同参数的方法。-->类优先原则
		//知识点4:如果实现类实现了多个接口,而这多个接口中定义了同名同参数的默认方法,
		//那么在实现类没有重写此方法的情况下,报错。-->接口冲突。
		//这就需要我们必须在实现类中重写此方法
		s.method3();
		
	}
	
}

class SubClass extends SuperClass implements CompareA,CompareB{
    
    
	
	public void method2(){
    
    
		System.out.println("SubClass:上海");
	}
	
	public void method3(){
    
    
		System.out.println("SubClass:深圳");
	}
	
	//知识点5:如何在子类(或实现类)的方法中调用父类、接口中被重写的方法
	public void myMethod(){
    
    
		method3();//调用自己定义的重写的方法
		super.method3();//调用的是父类中声明的
		//调用接口中的默认方法
		CompareA.super.method3();
		CompareB.super.method3();
	}
}


InterfaceCompareA:

package com.atguigu.java8;

/*
 * 
 * JDK8:除了定义全局常量和抽象方法之外,还可以定义静态方法、默认方法
 * 
 */
public interface CompareA {
    
    
	
	//静态方法
	public static void method1(){
    
    
		System.out.println("CompareA:北京");
	}
	//默认方法
	public default void method2(){
    
    
		System.out.println("CompareA:上海");
	}
	
	default void method3(){
    
    
		System.out.println("CompareA:上海");
	}
}



InterfaceCompareB:

package com.atguigu.java8;

public interface CompareB {
    
    
	
	default void method3(){
    
    
		System.out.println("CompareB:上海");
	}
	
}



Class SuperClass:

package com.atguigu.java8;

public class SuperClass {
    
    
	
	public void method3(){
    
    
		System.out.println("SuperClass:北京");
	}
	
}


5.5 Application of interface 1: proxy mode

Insert image description here
Insert image description here

package com.atguigu.java1;
/*
 * 接口的应用:代理模式
 * 以下代码为:静态代理模式
 * 
 */
public class NetWorkTest {
    
    
	public static void main(String[] args) {
    
    
		Server server = new Server();
//		server.browse();
		ProxyServer proxyServer = new ProxyServer(server);
		
		proxyServer.browse();
		
	}
}

interface NetWork{
    
    
	
	public void browse();
	
}

//被代理类
class Server implements NetWork{
    
    

	@Override
	public void browse() {
    
    
		System.out.println("真实的服务器访问网络");
	}

}
//代理类
class ProxyServer implements NetWork{
    
    
	
	private NetWork work;
	
	public ProxyServer(NetWork work){
    
    
		this.work = work;
	}
	

	public void check(){
    
    
		System.out.println("联网之前的检查工作");
	}
	
	@Override
	public void browse() {
    
    
		check();
		
		work.browse();
		
	}
	
}

5.6 Application of interface 2: Factory mode

Factory pattern : It realizes the separation of the creator and the caller, that is, shields and isolates the specific process of creating objects to achieve the purpose of improving flexibility.

Factory : used to create objects.

Classification of factory pattern :

  1. Simple factory model: used to produce any product in the same hierarchical structure. (For adding new products, existing code needs to be modified)
  2. Factory method pattern: used to produce fixed products in the same hierarchical structure. (Supports adding any product)
  3. Abstract factory pattern: used to produce all products of different product families. (There is nothing we can do about adding new products; we support adding product families)

5.7 First introduction to design patterns

There are 23 design patterns in Java, which are essentially the practical application of object-oriented design principles and a full understanding of the encapsulation, inheritance and polymorphism of classes, as well as the association and combination relationships of classes.
Of course, software design patterns are just a guide, and in actual software development, they must be chosen according to specific needs.
1. For simple programs, it may be easier to write a simple algorithm than to introduce a certain design pattern.
2. But for large-scale project development or framework design, it is obviously better to use design patterns to organize code.

5.7.1 Singleton design pattern concept

The singleton mode can be said to be the most used by most developers in practice. Common beans created by Spring are in the singleton mode.
The singleton mode has many benefits, such as saving system memory space and controlling resource usage.
The most important thing about the singleton pattern is to ensure that there is only one object.
To put it simply, it is guaranteed that there is only one object of a class in memory.
RunTime is a typical singleton design. We can get a glimpse of it through the analysis of the RunTime class.

5.7.2 Source code analysis

/**
 * Every Java application has a single instance of class
 * <code>Runtime</code> that allows the application to interface with
 * the environment in which the application is running. The current
 * runtime can be obtained from the <code>getRuntime</code> method.
 * <p>
 * An application cannot create its own instance of this class.
 *
 * @author  unascribed
 * @see     java.lang.Runtime#getRuntime()
 * @since   JDK1.0
 */
RunTime.java
package java.lang;
 
public class Runtime {
    
    
	//1、创建静态的全局唯一的对象
    private static Runtime currentRuntime = new Runtime();
 
	//2、私有构造方法, 
    /** Don't let anyone else instantiate this class */
    private Runtime() {
    
    }
 
	
 
//3、通过自定义的静态方法获取实例
    public static Runtime getRuntime() {
    
    
        return currentRuntime;
    }
}

5.7.3 Hungry Chinese Style

Purpose: To control the number of objects created by the outside world, only one object can be created .
Development steps:
1. Privatize the constructor
2. Create the object inside the class
3. Provide a public get() to the outside world and return a prepared object. Because the constructor is now private, the outside world cannot create an object to call the method. Only methods declared as static can be called through the class name.
4.No thread safety issues

package cn.tedu.single;
//测试单例设计模式	
public class Test8_Single {
    
    
	public static void main(String[] args) {
    
    
		Single s = Single.get();
		Single s1 = Single.get();
		
		//get()多少次,内存中使用的都是同一个对象
		System.out.println(s);//cn.tedu.single.Single@15db9742
		System.out.println(s1);//cn.tedu.single.Single@15db9742
	}
}
class Single{
    
    
//	1、私有化构造方法,不让外界直接new
	private Single() {
    
    }
	
//	2、在类的内部,创建好对象
	//static :静态只能调用静态,因为方法是静态的调用这对象属性也只能是静态的。
	static private  Single s = new Single();
	
//	3、对外界提供一个公共的get(),返回一个已经准备好的对象
//static是为了外界不通过对象访问而是通过类名直接方法	
	static public Single get(){
    
    
		//注意:静态只能调用静态
		return s;
	}
}

5.7.4 Lazy Man Style

The lazy style has thread safety issues - "solved in day05-java advanced programming -" synchronization lock.

Note: During the interview, you are required to write a singleton design pattern: either write a hungry Chinese style, or write a thread-safe lazy style, do not write a thread-unsafe lazy style.

class Single{
    
    
//	1、私有化构造方法,不让外界直接new
	private Single() {
    
    }
	
//	2、在类的内部,创建好对象
	//static :静态只能调用静态
	static private  Single s = null;
	
//	3、对外界提供一个公共的get(),返回一个已经准备好的对象
//static是为了外界不通过对象访问而是通过类名直接方法	
 static public Single get(){
    
    
		//注意:静态只能调用静态
		if(s==null){
    
    
		/*会有线程安全问题:假如现在多个线程,每个线程调用run方法,各个run方法有调用这个get方法。
         当第一个线程进入到这个get方法后,第一次进入对象为空,此时可能发生阻塞第二个线程进来判断为空
         也需要创建对象。这样就创建了2个对象不合理。s相当于共享数据。
         */
         //如何解决?查看在day05--java高级编程---》同步锁中解决。
           s = new Single();
       }
		return s;//是null说明还没有创建对象,不是null说明创建好了对象直接返回,可以保证只创建一次对象。
	}
}

5.7.5 The difference between hungry man style and lazy man style

Hungry Chinese style:

  1. Disadvantage: Object loading takes too long.
  2. Benefit: Hungry Chinese Style is thread-safe

Lazy man style:

  1. Benefit: Delays object creation.
  2. Disadvantages of the current way of writing: thread unsafe. —>When reaching multi-threaded content, modify it again (add synchronized lock)

5.7.6 Singleton Design Pattern-Application Scenario

Insert image description here

5.8 Expansion

5.8.1 Abstract Notes

Abstract methods require subclasses to override them after inheritance . So, which keywords cannot be used with the abstract keyword? The following keywords can be used in abstract classes, but they are meaningless.
1. Private: After being privatized, subclasses cannot be rewritten, which is contrary to abstract.
2. static: static, taking precedence over the existence of objects. Abstract methods need to be rewritten by subclasses, while static methods cannot be overridden, so the two are contradictory.
3. Final: After being modified by final, it cannot be rewritten, which is contrary to abstract.

5.8.2 The difference between interfaces and abstract classes

Insert image description here

1. Neither abstract classes nor interfaces can be instantiated directly. If they are to be instantiated, abstract class variables must point to subclass objects that implement all abstract methods, and interface variables must point to class objects that implement all interface methods.
2. Abstract classes must be inherited by subclasses, and interfaces must be implemented by classes.
3. Interfaces can only make method declarations, while abstract classes can make method declarations and method implementations.
4. Variables defined in interfaces can only be public static constants, while variables in abstract classes are ordinary variables.
5. All abstract methods in an abstract class must be implemented by the subclass. If the subclass cannot implement all the abstract methods of the parent class, then the subclass can only be an abstract class. Similarly, when a class implements an interface, if it cannot implement all interface methods, then the class can only be an abstract class.
6. Abstract methods can only be declared, not implemented. Interfaces are the result of design, and abstract classes are the result of reconstruction. 7.
There are no abstract methods in abstract classes. If you want to extend new methods of abstract classes, subclasses will easily These new methods are available.
8. If there is an abstract method in a class, then the class can only be an abstract class.
9. The abstract method must be implemented, so it cannot be static or private.
10. Interfaces can inherit interfaces, and can inherit multiple interfaces, but classes can only inherit from a single root.

5.8.3 Understand the opening and closing principle OCP of software design

Open function expansion, close source code modification, etc.

The full English name of the Open Close Principle is Open Close Principle, and the abbreviation is OCP. It is the most basic design principle in the Java world. It guides us how to build a stable and flexible system.

The definition of the open-closed principle is: objects (classes, modules, functions, etc.) in software should be open for extension, but closed for modification.

The opening and closing principle is a design pattern that emerged with the idea of ​​object-oriented programming.
Open means that it can be extended based on the source code, such as inheritance, interfaces, abstract classes, etc. In JAVA, inheritance is used to extend the functionality of a class library on the premise that it can be directly called. Applications do not need to understand the internal logic of the encapsulated class to develop.

Closed: It means that the original code is not allowed to be modified. So as not to affect other existing functions and cause functional paralysis.

5.8.4 Piling and DeBug

How do you debug the code when the results of the program are different from what you said you expected?

(1) Piling: System.out.println(data);

(2) Debug debugging tools: briefly, see the blog chat column for details.

5.8.5 The Math class provides three positive methods: ceil, floor, round

Writing method :

System.out.println(Math.ceil(11.5));//12.0

(1) The English meaning of ceil is the ceiling, and this method means rounding up.
(2) The English meaning of floor is the floor, and this method means rounding down.
(3) Round method: It means "rounding" (ie: +0.5 rounded down)

6 exception

6.1 Exception overview

  • Emergence background :
    In the process of project development using computer languages, even if programmers write the code well 尽善尽美, they will still encounter some problems during the operation of the system, because many problems cannot be avoided by relying on code, such as: 客户输入数据的格式,读取文件是否存在,网络是否始终保持通畅etc.

  • Exceptions :
    In the Java language, abnormal situations that occur during program execution are called "exceptions". (Syntax errors and logic errors during development are not exceptions)

6.2 Abnormal system

Insert image description here
Description :

  • Throwable: In Java, all exceptions have a common ancestor Throwable (throwable)
    • Error: Serious problem, no need to deal with it
    • Exception: Called an exception class, it represents a problem that the program itself can handle
      • RuntimeException: It is not checked during compilation. If a problem occurs, we need to come back and modify the code.
      • 非RuntimeException: It must be processed during compilation, otherwise the program cannot be compiled, let alone run normally.

6.2.1 Error examples

package com.atguigu.java;
/*
 * Error:
 * Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源耗尽等严重情况。比如:StackOverflowError和OOM。
 * 
 * 一般不编写针对性的代码进行处理。出现问题只能改代码。
 * 
 * 
 */
public class ErrorTest {
    
    
	public static void main(String[] args) {
    
    
		//1.栈溢出:java.lang.StackOverflowError
//		main(args);
		//2.堆溢出:java.lang.OutOfMemoryError 
		Integer[] arr = new Integer[1024*1024*1024];
		
	}
}

6.2.2 Exception examples

package com.atguigu.java1;

import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.Scanner;

import org.junit.Test;

/*
 * 一、异常体系结构
 * 
 * java.lang.Throwable
 * 		|-----java.lang.Error:一般不编写针对性的代码进行处理。
 * 		|-----java.lang.Exception:可以进行异常的处理
 * 			|------编译时异常(checked)
 * 					|-----IOException
 * 						|-----FileNotFoundException
 * 					|-----ClassNotFoundException
 * 					|-----SQLException sql异常
 * 			|------运行时异常(unchecked,RuntimeException)
 * 					|-----NullPointerException
 * 					|-----ArrayIndexOutOfBoundsException
 * 					|-----ClassCastException
 * 					|-----NumberFormatException 数字格式异常
 * 					|-----InputMismatchException 输入不匹配异常
 * 					|-----ArithmeticException 算术异常
 * 
 * 
 * 
 * 面试题:常见的异常都有哪些?举例说明
 */
public class ExceptionTest {
    
    
	
	//******************以下是编译时异常***************************
	@Test
	public void test7(){
    
    
//		File file = new File("hello.txt");
//		FileInputStream fis = new FileInputStream(file);
//		
//		int data = fis.read();
//		while(data != -1){
    
    
//			System.out.print((char)data);
//			data = fis.read();
//		}
//		
//		fis.close();
		
	}
	
	//******************以下是运行时异常***************************
	//ArithmeticException
	@Test
	public void test6(){
    
    
		int a = 10;
		int b = 0;
		System.out.println(a / b);
	}
	
	//InputMismatchException
	@Test
	public void test5(){
    
    
		Scanner scanner = new Scanner(System.in);
		int score = scanner.nextInt();
		System.out.println(score);
		
		scanner.close();
	}
	
	//NumberFormatException
	@Test
	public void test4(){
    
    
		
		String str = "123";
		str = "abc";
		int num = Integer.parseInt(str);
		
		
		
	}
	
	//ClassCastException
	@Test
	public void test3(){
    
    
		Object obj = new Date();
		String str = (String)obj;
	}
	
	//IndexOutOfBoundsException
	@Test
	public void test2(){
    
    
		//ArrayIndexOutOfBoundsException
//		int[] arr = new int[10];
//		System.out.println(arr[10]);
		//StringIndexOutOfBoundsException
		String str = "abc";
		System.out.println(str.charAt(3));
	}
	
	//NullPointerException
	@Test
	public void test1(){
    
    
		
//		int[] arr = null;
//		System.out.println(arr[3]);
		
		String str = "abc";
		str = null;
		System.out.println(str.charAt(0));
		
	}
	
	
}

6.3 JVM’s default processing solution

If there is a problem with the program and we do not do anything, the JVM will eventually do the default processing.

  • Information such as the name of the exception , the cause of the exception , and the location of the exception are output on the console (as can be seen from the figure below)
  • The program stops executing (as you can see from the picture below, 结束there is no output to the console)

Insert image description here

6.4 Member methods of Throwable

Insert image description here
Insert image description here

6.5 The difference between compile-time exceptions and run-time exceptions

Exceptions in Java are divided into two major categories: 编译时异常and 运行时异常, also known as 受检异常and 非受检异常All RuntimeException classes and their subclasses are called runtime exceptions, and other exceptions are compile-time exceptions.

  • Compile-time exception: must be handled explicitly, otherwise the program will cause an error and fail to compile
  • Runtime exceptions: no explicit handling is required, and can be handled in the same way as compile-time exceptions

6.6 Overview of exception handling

  • Why exception handling is necessary :
    ​​Because the default handling scheme of the Java virtual machine will cause the program to end directly where an exception occurs. In actual development, if a problem occurs in a certain part of our program, it should not affect subsequent execution, so we have to handle the exception ourselves.

  • If there is a problem with the program, we need to handle it ourselves. There are two options :

    • try … catch …
    • throws
  • Exception handling :catch and throw model

    • Process 1 : "Throw": During the normal execution of the program, once an exception occurs, an exception object will be generated at the exception code and the object will be thrown. Once the exception object is thrown,其后的代码就不会再执行。
      • Regarding the generation of exception objects :
        ① The exception object automatically generated by the system
        ② Manually generate an exception object and throw it (throw)
    • Process 2 : "Catch": can be understood as an exception handling method:
      • try-catch-finally: real exception handling, subsequent code会执行
      • throws: The exception is not actually handled but just thrown to the caller, subsequent code不会执行
  • If an exception occurs in the program and is not handled:

    • Eventually it will run into the main method. The main method is managed by the jvm virtual machine. The jvm virtual machine handles exceptions by killing the process and ending the program.
  • The meaning of exception handling:

    • Even after an exception occurs, the program can still be executed correctly without affecting program operation.

6.7 Exception handling method 1: (try-catch-finally)

Description :

  • try-catch-finally, also called capture mode.

Syntax :

//try只能而且出现一次  catch可以出现0到N次    finally出现0到1次  
try{
    
    
  	//可能出现异常的代码
  
  }catch(异常类型1 变量名1){
    
    
  		//处理异常的方式1
  }catch(异常类型2 变量名2){
    
    
  		//处理异常的方式2
  }catch(异常类型3 变量名3){
    
    
  		//处理异常的方式3
  }
 ....
  finally{
    
    
  		//一定会执行的代码
  }

Implementation process:

  • The program starts executing from the code in try
  • 出现异常,会自动生成一个异常类对象, the exception object will be submitted to the Java runtime system
  • When the Java runtime system receives an exception object, it will go to the catch to find the matching exception class, and handle the exception after finding it.
  • 执行完毕之后,程序还可以继续往下执行

6.7.1 Test 1: try-catch structure

package com.shuai;
/**
 * 1.finally是可选的。
 * 
 * 2.使用try将可能出现异常代码包装起来,在执行过程中,一旦出现异常就会生成一个对应类的异常对象,根据
 *   此对象的类型到catch中进行匹配。
 * 
 * 3.一旦try中的异常对象匹配到一个catch时,就进入catch中进行异常的处理,一旦处理完成,就跳出当前的
 *   try-catch结构(在没有写finally的情况),继续执行其后的代码。
 * 
 * 4.catch中的异常类型如果没有父子类关系,谁声明在上,,谁声明在下无所谓。
 *   catch中的异常类型如果有父子类关系,则要求子类在上父类在下,从小到大的排序,否则报错。
 * 
 * 5.常用的异常处理方式:1)String e.getMessage()  2)void e.printStackTrace() 这个比较常用
 * 
 * 6.在try结构中定义的变量,出了try结构以后就不能使用了。想要使用把变量声明在外面,赋值在结构里面。
 * 
 * 7.为什么不写成int num;而要多赋值个0,首先因为变量想要输出首先要声明好后并且有初始化的值,而局部变量
 *   没有默认值,一旦try中的程序报错,直接输出num,num没有值程序会报错,为了避免这种情况,加上0不会影响程
 *   序也不会因为异常情况导致num没有值而保错。
 * 
 *8.try-catch-finally也可以嵌套
 
 * 体会1:使用try-catch-finally结构处理编译异常时,使得编译时不会报错,但运行时有可能报错,相当于try-catch-finally
 *       将编译时可能出现的异常延迟到运行时出现。
 * 体会2:开发中,由于运行时异常比较常见,所以我们通常就不针对运行时异常编写try-catch-finally了。
 *       针对于编译时异常,我们说一定要考虑异常的处理。(如果与前端页面交互提示时,仍要处理。)
 */
public class Demo05 {
    
    
    public static void main(String[] args) {
    
    
        String str="123";
        str="abc";
        /*为什么不写成int num;而要多赋值个0,首先因为变量想要输出首先要声明好后并且有初始化的值,
        而局部变量没有默认值,一旦try中的程序报错,直接输出num,num没有值程序会报错,为了避免这种
        情况,加上0不会影响程序也不会因为异常情况导致num没有值而报错。*/

        int num = 0;
        try {
    
    
            num=Integer.parseInt(str);
            //int num=Integer.parseInt(str);//出现异常
            System.out.println("hell0-------01");//不会输出
        } catch (NullPointerException  e) {
    
     //习惯上异常名叫 e
            System.out.println("出现了空指针转换异常");
        }catch (NumberFormatException e) {
    
     //一个类型e只在一个catch中有效,所以不同的catch中名字可以相同。
            //System.out.println("出现了数值转换异常"); 一般不这样写,用异常类方法代替,如下:

            //String e.getMessage():此方法返回值是String类型,想要看就要输出它。因为有返回值就要定义变量进行接收,查看就要输出,这里简写一块了。
            // System.out.println(e.getMessage()); //打印异常信息

            //void e.printStackTrace():此方法返回值是void类型,不需要在进行输出就能查看。
            e.printStackTrace();  //打印异常详细信息


        }catch (Exception e){
    
    
            System.out.println("出现了异常");//不会输出
        }
        //System.out.println(num);报错不能调用,因为变量num在catch中定义的,作用域在catch中。
        System.out.println(num);
        System.out.println("hell0-------02");//会输出

    }

}

6.7.2 Test 2: finally usage scenario analysis

package com.atguigu.java1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.junit.Test;

/*
 * try-catch-finally中finally的使用:
 * 
 * 
 * 1.finally是可选的
 * 
 * 2.finally中声明的是一定会被执行的代码。即使catch中又出现异常了,try中有return语句,catch中有
 * return语句等情况。
 * 
 * 3.像数据库连接、输入输出流、网络编程Socket等资源,JVM是不能自动的回收的,我们需要自己手动的进行资源的
 *   释放。此时的资源释放,就需要声明在finally中。
 * 
 * 
 * 
 */
public class FinallyTest {
    
    
	
	
	@Test
	public void test2(){
    
    
		FileInputStream fis = null;
		try {
    
    
			File file = new File("hello1.txt");
			fis = new FileInputStream(file);
			
			int data = fis.read();
			while(data != -1){
    
    
				System.out.print((char)data);
				data = fis.read();
			}
			
			
		} catch (FileNotFoundException e) {
    
    
			e.printStackTrace();
		} catch (IOException e) {
    
    
			e.printStackTrace();
		}finally{
    
    
			try {
    
    
				if(fis != null)//如果文件没有创建成功为赋的默认值null会报空指针异常,加上if判断避免这一情况。
					fis.close();
			} catch (IOException e) {
    
    
				e.printStackTrace();
			}
		}
	}
	
	
	@Test
	public void testMethod(){
    
    
		int num = method();
		System.out.println(num);
	}
	
	public int method(){
    
    
		
		try{
    
    
			int[] arr = new int[10];
			System.out.println(arr[10]);
			return 1;
		}catch(ArrayIndexOutOfBoundsException e){
    
    
			e.printStackTrace();
			return 2;
		}finally{
    
    
			System.out.println("我一定会被执行");
			return 3;
		}
		
		
	}
	
	@Test
	public void test1(){
    
    
		try{
    
    
			int a = 10;
			int b = 0;
			System.out.println(a / b);
			
		}catch(ArithmeticException e){
    
    
			e.printStackTrace();
			
//			int[] arr = new int[10];
//			System.out.println(arr[10]);
			
		}catch(Exception e){
    
    
			e.printStackTrace();
		}
//		System.out.println("我好帅啊!!!~~");
		
		finally{
    
    
			System.out.println("我好帅啊~~");
		}
		
	}
	
}

Shortcut key: Select the code of the error package—>Suround With—>Try/catch Block
Insert image description here
Note: Modify the code to close the stream in finally.

Insert image description here

6.8 Exception handling method two: (throws)

  • Usage background:
    Although we can handle exceptions through try...catch..., we do not have the permission to handle exceptions in all situations. That is to say, sometimes exceptions that may occur cannot be handled by us. At this time What should we do?
    For this situation, Java provides a throws processing solution

  • Format:

throws 异常类名;
  • Note : This format is followed 方法的括号by

  • Compile-time exceptions must be handled . There are two handling options: try...catch or throws. If the throws option is used, whoever calls it will handle it in the future.

  • Runtime exceptions do not need to be handled . After a problem occurs, we need to come back and modify the code.

  • Execution process :

    • "throws + exception type" is written at the declaration of the method. Indicates the type of exception that may be thrown when this method is executed.
    • Once an exception occurs when the method body is executed, an object of the exception class will still be generated at the exception code. When this object meets the exception type after throws, it will be thrown.
    • 异常代码后续的代码,就不再执行!

Insert image description here

6.8.1 Case 1: Testing the throws keyword

package com.atguigu.java1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/*
 * 异常处理的方式二:throws + 异常类型
 *
 * 1. "throws + 异常类型"写在方法的声明处。指明此方法执行时,可能会抛出的异常类型。
 *     一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象,此对象满足throws后异常
 *     类型时,就会被抛出。异常代码后续的代码,就不再执行!
 *
 * 2. 体会:try-catch-finally:真正的将异常给处理掉了。
 *        throws的方式只是将异常抛给了方法的调用者。  并没有真正将异常处理掉。
 *
 * 3. 开发中如何选择使用try-catch-finally 还是使用throws?
 *   3.1 如果父类中被重写的方法没有throws方式处理异常,则子类重写的方法也不能使用throws,意味着如果
 *       子类重写的方法中有异常,必须使用try-catch-finally方式处理。
 *   3.2 执行的方法a中,先后又调用了另外的几个方法,这几个方法是递进关系执行的。我们建议这几个方法使用throws
 *       的方式进行处理。而执行的方法a可以考虑使用try-catch-finally方式进行处理。
 *
 */
public class ExceptionTest2 {
    
    


    public static void main(String[] args){
    
    
        try{
    
    
            method2();

        }catch(IOException e){
    
    
            e.printStackTrace();
        }

//		method3();

    }


    public static void method3(){
    
    
        try {
    
    
            method2();
        } catch (IOException e) {
    
    
        //IOException 是FileNotFoundException异常的父类,这里处理方式又相同所以只需要写一个catch即可。
            e.printStackTrace();
        }
    }

    //method1抛出了2个异常,这里method2调用为什么只抛出一个异常呢??
    //如果2个异常是父子类关系,并且处理异常的方式相同,比如都是e.printStackTrace();,那么只需要抛出一个异常即可。
    public static void method2() throws IOException{
    
    
        method1();
    }


    public static void method1() throws FileNotFoundException,IOException{
    
    
        File file = new File("hello1.txt");
        FileInputStream fis = new FileInputStream(file);

        int data = fis.read();
        while(data != -1){
    
    
            System.out.print((char)data);
            data = fis.read();
        }

        fis.close();

        System.out.println("hahaha!");
    }


}

Insert image description here
Insert image description here

6.8.2 Case 2: Test method rewritten in subclass throws exception smaller than parent class

One of the rules for method overriding: The exception type thrown by the overridden method of the subclass is not greater than the exception type thrown by the overridden method of the parent class.

package com.atguigu.java1;

import java.io.FileNotFoundException;
import java.io.IOException;

/*
 * 方法重写的规则之一:
 * 子类重写的方法抛出的异常类型不大于父类被重写的方法抛出的异常类型
 * 
 * 
 */
public class OverrideTest {
    
    
	
	public static void main(String[] args) {
    
    
		OverrideTest test = new OverrideTest();
		test.display(new SubClass());
	}

	
	public void display(SuperClass s){
    
    
		try {
    
    
			s.method();
		} catch (IOException e) {
    
    
			e.printStackTrace();
		}
	}
}

class SuperClass{
    
    
	
	public void method() throws IOException{
    
    
		
	}
	
	
}

class SubClass extends SuperClass{
    
    
//如果方法重写调用子类的方法的方法体,子类抛出的异常大于父类的,父类已经处理的异常在子类中不包含,则父类处理异常没有什么意义。
	public void method()throws FileNotFoundException{
    
    
		
	}
}

6.9 Manually throwing exception objects (throw)

  • Use background : as shown below.

  • Function : Used to throw exception objects inside the method body

  • Regarding the generation of exception objects :

    • Exception objects automatically generated by the system
    • Manually generate an exception object and throw it
  • Note : If an exception is thrown manually, it does not need to be handled if it is a runtime exception object. If it is a compile-time exception object, the exception must be handled.

6.9.1 Before manually throwing the exception object

Insert image description here

package com.atguigu.java2;

public class StudentTest {
    
    
	
	public static void main(String[] args) {
    
    
		
			Student s = new Student();
			s.regist(-1001);
			System.out.println(s);//直接输出对象的引用实际上时输出.toString()方法。
		
	}
	
}


class Student{
    
    
	
	private int id;
	
	public void regist(int id)  {
    
    
		if(id > 0){
    
    
			this.id = id;
		}else{
    
    
			/*
			 * 即便你此时输入的是负数不合理,只能给你个提示输入的数据错误,但是这样写还是把结果输出了。
			 * 正常来讲:应该是输入的是负数不合理,程序直接报错不会再向下执行输出结果,所以这里一般是手动抛出异常对象,
			 *        一旦数据不合理直接报异常,程序停止运行。
			 */
			System.out.println("您输入的数据非法!");
			
		}
		
	}

	@Override
	public String toString() {
    
    
		return "Student [id=" + id + "]";
	}
	
	
}

6.9.2 After manually throwing the exception object

package com.atguigu.java2;

public class StudentTest {
    
    
	
	public static void main(String[] args) {
    
    
		try {
    
    
			Student s = new Student();
			s.regist(-1001);
			System.out.println(s);
		} catch (Exception e) {
    
    
//			e.printStackTrace();

         		
			/*throw new RuntimeException("您输入的数据非法!")里面的值是由RuntimeException的有参构造方法中super(xxx)调用--->
			 * 父类的Exception的有参构造方法中super(xxx)调用----> Throable中的有参构造方法,在Throable类中通过有参构造方法
			 * 赋值(this.detailMessage = message;) 给成员变量: private String detailMessage;为:您输入的数据非法!
			 * 即:值最终赋值给Throable类的成员变量detailMessage。
			 * 			 					 	
			 * void e.getMessage() 底层源码:
			 * public String getMessage() {
             *     return detailMessage;
             *  }
			 * 这个方法getMessage()的返回值为Throable类中的detailMessage成员变量,所以输出结果为:您输入的数据非法! */
			System.out.println(e.getMessage());
		}
	}
	
}


class Student{
    
    
	
	private int id;
	
	public void regist(int id) throws Exception {
    
    
		if(id > 0){
    
    
			this.id = id;
		}else{
    
    
//			System.out.println("您输入的数据非法!");
			//手动抛出异常对象
//			throw new RuntimeException("您输入的数据非法!");抛出运行时异常,调用方不用处理。
//			throw new Exception("您输入的数据非法!");Exception包含编译器异常,所以一旦throws抛出,在调用方一定要进行处理编译器异常。
			throw new MyException("不能输入负数");//抛出的是自定义异常
			//错误的 String不是异常类
//			throw new String("不能输入负数");
//return 0;如果方法有返回值且不影响结果,则可以用throw代替return,因为如果报异常也会结束方法运行。

		}
		
	}

	@Override
	public String toString() {
    
    
		return "Student [id=" + id + "]";
	}
	
	
}

6.9.3 The difference between throw and throws

Insert image description here

6.10 Custom exceptions

Use background:

  • The purpose is that the exception type provided by the system is that 有限的if the exception generated by the program is not provided, you can throw your own defined exception to make the exception type 更加精确(usually used in conjunction with throw)
  • Generally this custom exception class, 定义这个类时要做到见名知意.

Format:
Insert image description here
Example:
Insert image description here

6.10.1 Testing

Used in conjunction with Case 6.9.2.

package com.atguigu.java2;
/*
 * 如何自定义异常类?
 * 1.继承于现有的异常结构:RuntimeException 、Exception(包含运行和编译器异常,
 *    所以编译期就要进行处理异常)
 *   RuntimeException异常:只需要继承RuntimeException异常或者它的子类。
 *   Checked异常:只需要继承Exception异常或者Exception的子类,但需要除RuntimeException之外。
 * 2.提供全局常量:serialVersionUID
 * 3.提供重载的构造器
 * 
 */
public class MyException extends Exception{
    
    
	
	static final long serialVersionUID = -7034897193246939L;
	
	//无参构造方法
	public MyException(){
    
    
		
	}
	//有参构造方法
	public MyException(String msg){
    
    
	/*
		 * 调用父类的有参构造,因为上面的案例中处理异常使用的是e.getMessage()方法,
		 * 这个方法返回值为Throable的成员变量dtailMessage属性。而现在自定义异常对象
		 * 的通过有参构造方法创建对象并传参,这个自定义异常对象的参数不是自己定义的而是定义
		 * 在顶级父类Throable中的成员变量,所以想要赋值给父类Throable的属性需要在子类
		 * 的构造方法中通过super一步一步调用父类构造方法,最终在Throwable的构造方法中把
		 * 值赋值给成员变量dtailMessage。
		 */
		super(msg);
	}
}

7. Inner classes

Insert image description here

7.1 Member inner class (static/non-static)


package com.atguigu.java2;
/*
 * 类的内部成员之五:内部类
 * 1. Java中允许将一个类A声明在另一个类B中,则类A就是内部类,类B称为外部类
 * 
 * 2.内部类的分类:成员内部类(静态、非静态)  vs 局部内部类(方法内、代码块内、构造器内)
 * 
 * 3.成员内部类:
 * 		一方面,作为外部类的成员:
 * 			>调用外部类的结构
 * 			>可以被static修饰
 * 			>可以被4种不同的权限修饰
 * 
 * 		另一方面,作为一个类:
 * 			> 类内可以定义属性、方法、构造器等
 * 			> 可以被final修饰,表示此类不能被继承。言外之意,不使用final,就可以被继承
 * 			> 可以被abstract修饰
 * 
 * 
 * 4.关注如下的3个问题
 *   4.1 如何实例化成员内部类的对象
 *   4.2 如何在成员内部类中区分调用外部类的结构
 *   4.3 开发中局部内部类的使用  见《InnerClassTest1.java》
 * 
 */
public class InnerClassTest {
    
    
	public static void main(String[] args) {
    
    
		
		//创建Dog实例(静态的成员内部类):
		Person.Dog dog = new Person.Dog();
		dog.show();
		//创建Bird实例(非静态的成员内部类):
//		Person.Bird bird = new Person.Bird();//错误的
		Person p = new Person();
		Person.Bird bird = p.new Bird();
		bird.sing();
		
		System.out.println();
		
		bird.display("黄鹂");
		
	}
}


class Person{
    
    //外部类
	
	String name = "小明";
	int age;
	
	public void eat(){
    
    
		System.out.println("人:吃饭");
	}
	
	
	//静态成员内部类
	static class Dog{
    
    
		String name;
		int age;
		
		public void show(){
    
    
			System.out.println("卡拉是条狗");
//			eat();
		}
		
	}
	//非静态成员内部类
	class Bird{
    
    
		String name = "杜鹃";
		
		public Bird(){
    
    
			
		}
		
		public void sing(){
    
    
			System.out.println("我是一只小小鸟");
			Person.this.eat();//调用外部类的非静态属性 属性不同名可以省略为:eat();
			eat();
			System.out.println(age);
		}
		
		public void display(String name){
    
    
			System.out.println(name);//方法的形参
			System.out.println(this.name);//内部类的属性
			System.out.println(Person.this.name);//外部类的属性 属性不同名可以省略
		}
	}
	
	
	public void method(){
    
    
		//局部内部类
		class AA{
    
    
			
		}
	}
	
	{
    
    
		//局部内部类
		class BB{
    
    
			
		}
	}
	
	public Person(){
    
    
		//局部内部类
		class CC{
    
    
			
		}
	}
	
	
	
}

7.2 Local inner classes (anonymous/non-anonymous)

package com.atguigu.java2;

public class InnerClassTest1 {
    
    
	
	
	//开发中很少见
	public void method(){
    
    
		//局部内部类
		class AA{
    
    
			
		}
	}
	
	
	//返回一个实现了Comparable接口的类的对象
	public Comparable getComparable(){
    
    
		
		//创建一个实现了Comparable接口的类:局部内部类
		//方式一:
//		class MyComparable implements Comparable{ //Comparable为源码里面的接口
//
//			@Override
//			public int compareTo(Object o) {
    
    
//				return 0;
//			}
//			
//		}
//		
//		return new MyComparable();
		
		//方式二:
		return new Comparable(){
    
    

			@Override
			public int compareTo(Object o) {
    
    
				return 0;
			}
			
		};
		
	}
	
}

Guess you like

Origin blog.csdn.net/aa35434/article/details/131211524