Day02 -- object oriented, construction method, code block explanation, this super, static, final, access modifier, method rewriting, up / down modeling, abstract class, interface, exception, internal class, design pattern

Cool breeze AAA 2022-02-13 07:38:49 阅读数:144

day02 day object oriented construction

1 Day06– object-oriented 1

1.1 object-oriented

1.1.1 Concept

Recommended books :Thinking in java

Concept : The so-called object-oriented is a programming idea , Through this kind of thinking, we can simplify the complicated things in our life , From the original executor to the commander , Object oriented is based on process oriented .

Advantages and disadvantages of process oriented structured design :
1). shortcoming : Lack of encapsulation of data .
2). shortcoming : Data and methods ( Operating data ) It's hard to separate .
3). advantage : High performance .

Advantages and disadvantages of object-oriented design :
1). advantage : Easy maintenance , Easy to expand , Easy to reuse .
2). shortcoming : Performance is lower than process oriented .

 Process oriented emphasizes process , for example :
1、 Open the refrigerator 2、 Put the elephant in 3、 Turn off the fridge.

 Object oriented emphasizes results , for example :
1、 I'm hungry , Go to the platform and order , This action is object-oriented . You didn't go to the market to buy vegetables, wash vegetables and cook ... As long as there is app That's all right. .
2、 The clothes are dirty , Throw the ticket directly to the woman and wait to wear it clean . You don't pay attention to the process in the middle .. Just find a good partner .
3、 The interviewer asked what object orientation is ? You answer that everything is an object !! Not recommended, because you haven't reached this depth yet , Best example . like , You say empty is color, color is empty — I‘m not buying it .

What we often say Object oriented programming Realization (OOP,Object Oriented Programming

The essence of object-oriented is : Organize code as a class , Encapsulating data in the organization of objects .

1.1.2 Three characteristics

1. encapsulation : Encapsulation realizes the of software components “ High cohesion 、 Low coupling ”, Prevent the impact of changes caused by program dependence .
(1) class : It encapsulates the properties and behavior of objects
(2) Method : It encapsulates the implementation of specific business logic functions
(3) Access control modifiers : It encapsulates specific access rights

2. Inherit : Inheritance improves the reusability and scalability of software .
(1) effect : Easy to reuse code , Reduce code redundancy , Improve program maintainability and scalability
(2) Superclass : Properties and behaviors common to all derived classes
Interface : Behavior shared by some derived classes
Derived class : Properties and behaviors unique to derived classes
(3) Classes and classes inherit directly from each other , There are multiple inheritance between interfaces , Class and interface are multiple implementations

3. polymorphic : Polymorphism enhances the flexibility and scalability of software .
(1) classification :
(1.1) Polymorphism of behavior ( For example )
(1.2) The polymorphism of the object ( For example )
(2) Look up 、 Cast 、instanceof Judge
(3) Forms of polymorphism
(3.1) rewrite : Show polymorphism according to different objects
(3.2) heavy load : Show polymorphism according to different parameters

1.1.3 Expand : Value passing and reference passing

standard : A project should have only one main startup class
java It's worth passing on .

package com.shuai;
public class Demo01 {

// Value passed 
public static void main(String[] args) {

int a = 1;
System.out.println(a);//1
change(a);
System.out.println(a);//1 No modification succeeded 
}
public static void change(int a) {
 // The return value is null 
a=10;
}
}
package com.shuai;
public class Demo01 {

// Value passed 
public static void main(String[] args) {

int a = 1;
System.out.println(a);//1
change(a);
System.out.println(a);//1 No modification succeeded 
}
public static void change(int a) {
 // The return value is null 
a=10;
}
}

1.2 Classes and objects

1.2.1 class

1、Java Most language Basic unit It's class , Similar to type .
2、 A class is an abstraction of a class of things .( Category / type , Represents a class of individuals )
3、 It can be understood as Templates perhaps Design drawings .
4、 Classes in the same package can be used with each other , But not the same name ( Must be saved after ).
5、 grammar : class Class name { }
6、 Classes generally contain :

  1. Properties common to all objects / features -------- Member variables
  2. Behavior common to all objects ------- Method

Classes in the same package can directly access , Classes in different packages cannot be accessed directly , Want to visit :

  1. First import Declare a fully named class ( Package name + Class name ), Then access the class ( Namely new An object )
  2. The full name of the class ------- Too complicated 、 Don't suggest ( It's too much trouble to write one statement after another )

Be careful : One .java There can be multiple class, But ask for , By public The decorated class can only have one , And the class name is the file name ( Case sensitive , Or there can be no one public Modified class ). Different files can have multiple public. So it's possible to write more than one document public

1.2.2 object

object : A real individual .

Each object has three characteristics : Object's state , Object's Behavior And objects identification .

1、 The state of an object is used to describe the basic characteristics of an object .
2、 The behavior of an object is used to describe its function .
3、 Object identification means that an object has a unique address in memory to distinguish it from other objects .
4、 A class is an abstraction of a class of things , Objects are concrete implementations .
5、 grammar : new Class name ();
6、 Every time new Will create a new object .
7、 Use new Keyword creates an object and allocates space 2 thing : Default initialization ( Assign default values to variables ) And call the constructor .

Calling member variables and methods ( When you create an object )

 The name of the reference type . Local variable name = assignment ;
The name of the reference type . Method calls ;

Why create objects : Because of the visit , Access is to access the things in the class , Variables and methods , Because only after instantiation , To put this object in memory , Then call within the specified range

1.2.3 The relationship between classes and objects

1、 Computer language is used to describe things in the real world . attribute + Behavior
2、 How to get through java What about language description ? Describe things through classes , Treat the attributes of things as Member variables , Think of behavior as Member method .
3、 A class can create multiple objects .

summary : Class is a template for an object , An object is a concrete instance of a class .

Take mobile phones for example

 attribute : Color , Size , brand , Price .
Method : Make a phone call , texting , Listen to the music .
class : Mobile phones , Extract the same attributes and behaviors
object : Many mobile phones can be produced according to the template , such as 1 Phone number object , Contains unique member variables and member methods

 Insert picture description here

1.3 Creation and use of classes and objects

1.3.1 practice 1: Class is created using

adopt class Keyword to create a class , adopt new Keyword to create an object .
1).

public class Test1_CreateObject {

public static void main(String[] args) {

// Create object test 
//3, By keyword new To create objects 
//new Phone() Anonymous object , Only one job at a time 
//new Phone().call(); There is only one thing to do 
//4,p yes Phone A type is a variable that references a type , Refer to the ,,, Address value in memory 
Phone p = new Phone();
// Creation of reference type , The default value for the reference type is null, The reference type is consistent with the object class name of the instance it needs .
//p On behalf of Phone object , Can you really use template defined functions ???
// Calling method 
p.call();
p.message();
p.music();
// Setting property values 
p.color="green"; // Change the value when calling 
p.size=6;
p.pinpai="HUAWEI";
p.price=20000;
// Call the property 
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, Create mobile class , Used to describe mobile phone things 
//2, General description : The characteristics of things + The behavior of things 
class Phone{

// The characteristics of things -- Member variables / Member attribute 
// features : Color , Size , brand , Price 
String color;
int size;
String pinpai;
double price;
// The behavior of things -- Member method / Member functions 
// Behavior / function : Make a phone call , texting , Listen to the music 
// Modifier Return value Method name ( parameter list ){ Method body }
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;
// practice 
public class Test2_Car {

public static void main(String[] args) {

//2, establish Car Object test 
Car c = new Car();
// Call function 
c.run();
c.stop();
// Setting property values 
c.color="red";
c.model="BMW5";
c.pinpai="BMW";
// Direct output variables 
System.out.println(c.color);
System.out.println(c.model);
System.out.println(c.pinpai);
}
}
//1, establish Car class , Used to describe things like cars 
class Car{

// -- features + Behavior 
String color;
String model;
String pinpai;
public void run() {

System.out.println(" Flying ");
}
public void stop() {

System.out.println(" Parking ");
}
}

1.3.2 Object storage in memory

Java Divide memory into 5 A large area , Memory by JVM Managed , We focus on stacks and heaps .
 Insert picture description here

  1. In general, local variables exist on the stack , After the method is executed, the memory is released ( A stack is smaller than a heap )
  2. object (new What came out ) In the pile , When the object is no longer in use , Memory will be released
  3. Each element of heap memory has an address value
  4. All attributes in an object have default values
  5. Address values are unique and will not be repeated ( Save address value , It takes up less memory space )
  6. The stack is : First in, second out ( It's like loading a bullet ) Pile up : Without this principle , You can put it anywhere .
  7. Memory by JVM Managed : Load the class first , In the load .class Will be assigned in the method area , Redistribute the heap , In the distribution stack ( Stack and heap start almost at the same time )
  8. Object has address value only after initialization
  9. Stack : Release after method execution . Pile up : Free memory when called when there are no references .

Stack , Pile up , What is stored in the method area ?

Stack : local variable ( Include method parameters , Also called local variables ), Save the address value of a corresponding object .
Pile up :new Out object ( Including instance variables and methods ).
Method area :.class Bytecode file ( Static methods and static variables ) In class , Only loaded once .

1.3.3 Single object memory graph

 Insert picture description here

Noun : Out of the stack

1.3.4 practice 2: Create multiple objects

package cn.tedu.oop;
// Test the creation and use of multiple objects 
public class Test3_Person {

public static void main(String[] args) {

// Create object test (addr: Address brand: brand )
Person p = new Person();
p.game(); // When calling a method, you can pass parameter assignment 
p.code();
// Setting property values : Assign values when calling properties 
p.name="rose";
p.age=20;
p.gender=1;
p.address=" Beijing ";
// Print 
System.out.println(p.name);
System.out.println(p.age);
System.out.println(p.gender);
System.out.println(p.address);
8888888888888888888888888
// Create multiple objects , Each object can change its value using the template ( Is the same class object , You can use the properties assigned by the last instantiated object )
Person p2 = new Person();
p2.code();
p2.game();
//TODO Setting property values 
System.out.println(p2.name);
System.out.println(p2.age);
System.out.println(p2.gender);
System.out.println(p2.address);
//p3 Is a variable of reference type , Nothing here new, There is no new space in heap memory .
//p3 Save the p2 Saved address value 
Person p3 = p2;
}
}
// establish Person class 
class Person{

// features 
String name;
int age;
int gender;//0 male 1 Woman 
String address;
// Behavior 
public void code() {

System.out.println(" Knock on the code ");
}
public void game() {

System.out.println(" Eat chicken ");
}
}

1.3.5 Multi object memory graph

 Insert picture description here

1、 Variable p And variables p2 Not a space ,p1 New space needs to be opened up
2、Person p2=new Person, At this time As long as there is new, New space will be created to store objects in heap memory .

1.4 encapsulation

1.4.1 summary

Encapsulation refers to hiding the attributes and implementation details of an object , Only provide public access to the outside world .
benefits
1、 Improve safety
2、 Improve reusability
Case study
1、 class
2、 Method

1.4.2 private keyword

Is a permission modifier , Used to modify Member variables and member functions , Privatized members can only be accessed in this class . If you want to modify, you can only access the public information provided externally get and set Method .

encapsulation , utilize private Keyword implementation , The purpose is to improve safety , This category .
such as : One public int age. The outside world can call it at will. If the assignment is 10000 year , Obviously unreasonable .
General packaging : attribute ( Member variables ) Privatization Act openly

1.4.3 practice 1: Encapsulate students

Create a student class , Create student object test

package cn.tedu.oop;
// Test package 
public class Test4_Private {

public static void main(String[] args) {

// Create student object test 
Student s = new Student();
// Call function 
// s.study();// because study() By private Modify the , In addition to their own classes , No other class can be used 
s.sleep();
// System.out.println(s.name);// because name By private Modify the , In addition to their own classes , No other class can be used 
//3, If I just want to modify it, it has been private Of name The value of the property ? -- Access public set()
// s.name ="jack";// cannot access 
s.setName("jack"); // call set Method assignment 88888888888
//4, If the outside world just wants to get private Of name The value of the property ? -- Access public get()
// System.out.println(s.name) ;// cannot access 
System.out.println(s.getName());// Different from the usual output , This is a direct output method .( because get Method returns a value. Generally, the front is to define a variable to accept , So this place can directly output methods )
}
}
// Create a student class 
class Student{

// Member attribute 
//1.1, encapsulation : Member variables , Encapsulated variables , No direct access from the outside world , Need indirect access to public set() Set the value ,get() Get value There are shortcut keys :source------get and set
private String name;
//3.1, Provide a public modification method -- setXxx() no return value 
public void setName(String n) {

// Get n after , Need to put n The value of is assigned to name
name = n;
}
//4.1, Provide a public access method -- getXxx() There is a return value 
public String getName(){

//4.2, adopt return keyword , hold name The value of the property , Return to the call location 
return name;
}
//TODO Encapsulate the following three properties , And provide set()/get()
private String subject;
public void setSubject(String s) {

subject = s ;
}
public String getSubject() {

return subject;
}
private int sno;
private int age;
//eclipse Automatic code generation : Right click -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;
}
// Member method 
//1, encapsulation : utilize private Keyword implementation , The purpose is to improve the security of the code , By private after , Resources can only be seen in this class 
private void study() {

System.out.println(" Is learning ");
}
public void sleep() {

//2, If the outside world still wants to implement study(), Access to public sleep(), Indirect access study() 
study();
System.out.println(" be sleeping ");
}
}

1.5 expand

1.5.1 The process of creating objects

Person p = new Person();// A lot has happened in this short line of code
1. hold Person.class File loaded into memory
2. In stack memory , Open up space , Store variables p
3. In heap memory , Open up space , Deposit Person object
4. Initialize member variables by default
5. Initialize the display of member variables
6. Execute construction ( If there are building blocks , Execute the construction code block first and then the construction method )
7. Heap memory complete
8. Assign the address value of heap memory to variable p ,p It's just a reference variable , Refer to the Person Object's address value

1.5.2 Anonymous object

Objects without names , Is a simplified representation of an object .
Use scenarios : When the called object is called only once .

advantage : Save memory , Efficient . Because it releases memory immediately after one call
shortcoming : limitations , Its properties can only be used once .

Demo d = new Demo();
d.sleep();
d.game();
// This d It's the name of the object .
Or you could write it as :
new Demo().show();// Created an object calling method 
new Demo().game();// Another object calling method is created 

2 Day07– object-oriented 2

2.1 Construction method ( Constructors , Builder , Constructors ,constructor)

2.1.1 Concept

  1. The construction method is a special method , It's a With the same name as the class and no return value The location of ( even void None ). Common methods can also be the same as the class name , But it doesn't usually say that .
  2. The creation of objects is accomplished by constructing methods ,
  3. Its function is to complete the creation of objects or the initialization of objects .
  4. When a class instantiates an object, it automatically calls the constructor .
  5. Constructors, like other methods, can be overloaded , But you can't rewrite .( because :1. Constructor cannot be inherited : If inherited, it is the same as the subclass class name .2. Because there are super Automatically call the constructor of the parent class )
  6. If you don't define a construction method , A parameterless constructor is provided by default ( So any class has a constructor ) If you define a construction method , Then... Is no longer provided by default , Therefore, it is recommended to manually write a parameterless structure .
  7. The function of construction method : In order to facilitate the creation of objects by the outside world .

idea Generate construction method shortcut :alt+insert.

2.1.2 form

 Modifier Class name ([ parameter list ]){
// There can be no participation or participation 
Code ……
// no return value 
}

2.1.3 practice 1: Constructor creates object

package cn.tedu.constructor;
// Use of test construction methods 
public class Test5_Constructor {

public static void main(String[] args) {

// establish Teacher test 
//1, When you create an object , The constructor will be called automatically ???-- Automatically called , Call the parameterless construction that will exist by default 
Teacher t = new Teacher();
//3.1, When you create an object , Trigger the parameter structure , Automatically call the constructor according to different parameter types .
Teacher t1 = new Teacher("tony");
}
}
// establish Teacher class 
class Teacher{

//2, Provide construction method : Modifier Class name ([ parameter list ]){}
//4, No arguments structure -- The default will exist -- Premise is : When there is no parametric structure , Just exist . If only a parameter containing construct is provided , There is no reference .
public Teacher() {

System.out.println(" No arguments structure ...");
}
//3, The construction method is a special method , Special when there is no return value , Method name = Class name . However, there can be overloading of methods 
// Prepare overloaded construction methods 
public Teacher(String n) {

System.out.println(" Parametric structure ..."+n);
}
}

2.1.4 practice 2: Construction method assignment

package cn.tedu.constructor;
// This class is used to test constructor assignment 
public class Test6_Constructor2 {

public static void main(String[] args) {

// Automatically trigger parameterless construction 
Student2 s = new Student2();
// Trigger the parameter structure , Assign values to member variables when creating objects .
Student2 s2 = new Student2(2);
}
}
// establish Student2 class 
class Student2{

// Member variables 
int age;
// Provide construction method 
public Student2() {

System.out.println(" No arguments structure ");
}
// Provide overloaded construction methods 
public Student2(int a) {
 //a Inside the method are local variables 
//1, Constructors can be used to assign values to variables 
// technological process : When creating objects with parameters , It will automatically trigger the parameter structure . Put parameters 2 to a assignment ,a After getting the value, give the member variable age assignment 
age = a;
System.out.println(" Member variables age:"+age);
System.out.println(" Parametric structure ");
}
}

2.2 Building code blocks and local code blocks

2.2.1 Building blocks of code

1、 Inside the class , Method external , Code block for .
2、 Usually It is used to extract the common code in the construction method .
3、 The construction code block is called before each call to the construction method
4、 Prior to constructor loading
5、 Each time an object is created, the construction code block is called first , When calling the constructor

6、{ }

Test construction code block :

package cn.tedu.block;
//1, When you create an object , The constructor will be triggered automatically . If there is a construction code block, it will execute the code block first and then the construction method 88888888888888888888888888
public class Test1_Block {

public static void main(String[] args) {

//TODO establish Person Object test 
new Person();
//2, Construction code blocks and construction methods are called each time an object is created 
new Person();
new Person("name");
new Person(100);
}
}
// establish Person class 
class Person{

String country;// Let each method be constructed for , Improve the scope of action 
//b, Provide construction code blocks : Location : Inside the class, outside the method 
{

//3, Building blocks of code : Used to extract the commonness of construction methods 
country = " Chinese ";
}
//a, Provide construction method 
public Person() {

System.out.println(" No arguments structure ..., My nationality is :"+country);
}
//c, Provide overload construction method 
public Person(String c) {

System.out.println(" Parametric structure ..., My nationality is :"+country);
}
public Person(int a) {

System.out.println(" Parametric structure ..., My nationality is :"+country);
}
}

2.2.2 Local code block

1、 stay Method inside ( Both ordinary methods and construction methods can ) Code block for
2、 Usually The scope of action used to control variables , The parentheses are invalid
3、 The smaller the range of variables, the better , Member variables have thread safety problems
4、 Method call triggers
5、 Local code blocks are called when a method is called .
6. { }

2.2.3 test : structure , Local code block loading order

Building blocks of code -> Construction method -> Local code block

package cn.tedu.block;
// Test code block 
//1, When you create an object , The constructor will be triggered automatically . If there is a construction code block, it will execute the code block first and then the construction method , If local code block is written in constructor , The order of construction methods and local code blocks depends on the order in which the program writes code . If it's written in a common way , Is used when calling ( It is the last use , Because the object is created first , When calling a method by reference ).
// summary :
//1, Building blocks of code : Triggered when an object is created , Inside the class, outside the method , Used to extract commonalities of construction methods 
//2, Local code block : Method call triggers , In the method , Used to control the scope of the variable 
// If no object is created , Building blocks of code does not automatically execute 
//2. Construction code blocks and construction methods are called each time an object is created 
public class Test1_Block {

public static void main(String[] args) {

//TODO establish Person Object test 
new Person();
//2, Construction code blocks and construction methods are called each time an object is created 
new Person();
new Person("name");
new Person(100).sleep();// Trigger local code blocks 
}
}
// establish Person class 
class Person{

String country;// Let each method be constructed for , Improve the scope of action 
//b, Provide construction code blocks : Location : Inside the class, outside the method 
{

//3, Building blocks of code : Used to extract the commonness of construction methods 
country = " Chinese ";
}
//a, Provide construction method 
public Person() {

System.out.println(" No arguments structure ..., My nationality is :"+country);
}
//c, Provide overload construction method 
public Person(String c) {

System.out.println(" Parametric structure ..., My nationality is :"+country);
}
public Person(int a) {

System.out.println(" Parametric structure ..., My nationality is :"+country);
}
// Provide common methods 
public void sleep() {

// Local code block : Location : In the method + effect : The control range of the variable 
{

int i = 10;
System.out.println(" Local code block ..."+i);
}
// System.out.println(i);
}
}

2.3 this keyword

2.3.1 Concept

explain
1.this A reference object that represents the object of this class .
2.this Only in 2 A place to : One is , The member variable name and local variable name are the same , use this Member variables are used to distinguish between member variables and local variables . The other is , Used to call between constructor methods. Another constructor uses... In the first line .

Be careful
1. When the names of member variables and local variables are different, you can omit this.
2. In the constructor ,this() Must be on the first line .

2.3.2 form

name=name;
age=age;
// explain : Actually, I want to Student Class name The value of is assigned to the member variable , It's equivalent to what you want to do :
Student.name=name;
// But you can't write the class name directly , In this case, the object representing this class is used this To complete . The code becomes :
this.name=name;

grammar :

1)this. Member variable name ----------- Access member variables ( master )
this.name=name;
2)this. Method name ()------------ Calling method ( No need to master )
Because there is no same method in the class , So you don't have to write this To distinguish between .
3)this()------------------ Call constructor ( Only overloaded classes with the same name ) According to its parameter list
( A construction method can be achieved by this Keyword calls another overloaded constructor )

2.3.3 practice 1: When the variable names are the same

When a local variable and a member variable have the same name , Used to distinguish .
If there is a variable with the same name nearby , Will follow the principle of proximity of variables , So how to call member variables ?

package cn.tedu.thisdemo;
// test this keyword 
public class Test2_This {

public static void main(String[] args) {

// establish Student Object test 
Student s = new Student();
s.show();
}
}
The code is 1// establish Student class 
class Student{

int count ;// Member variables 
int sum = 20;// Member variables 
public void show() {

int sum = 10;// local variable 
System.out.println(sum);//10, Nearby principle 
System.out.println(count);//0
// System.out.println(new Student().sum);//20
//1,this Keyword represents a reference to this kind of object, which is equivalent to Student this = new Student();8888888888888888888
//2, When a member variable and a local variable have the same name ( Such as :sum), have access to this To distinguish between .this What is called is the original member variable .888888888888888888888888( When the names of member variables and local variables are different, you can omit this)
//( Because local variables are in the method , If you want to call, call the method first , So the variable it calls is a member variable )
System.out.println(this.sum);//20
}
}
The code is 2class Student2{

String name;
// When you create an object , Give member variables name assignment 
public Student2(String name) {

// name = name;// Failed to give member variables name assignment , Because both sides of the equal sign are local variables // Nearby principle 
this.name = name;// To the left of the equal sign is the member variable , On the right is the local variable 
// Be careful : Variables are local variables as long as they are methods , Not in { } It's inside .
System.out.println(name);
System.out.println(this.name);
}
}

2.3.4 practice 2: Calls between constructor methods

package cn.tedu.thisdemo;
//this Call... Between constructor methods 
// summary :this Only in 2 A place to : One is , The member variable name and local variable name are the same , use this Member variables are used to distinguish between member variables and local variables . The other is , Used to call between constructor methods. Another constructor uses... In the first line 
//1,this You can call each other between constructor methods 
//2, If in the construction method this keyword , It must be placed in the position of the first statement 
// Constructors cannot call each other at the same time , Otherwise, there will be a dead cycle , Report errors .
public class Test3_This2 {

public static void main(String[] args) {

// Create object tests without parameters 
Teacher t = new Teacher();
// Create object test with parameters 
Teacher t2 = new Teacher("jack");
}
}
// establish Teacher class 
class Teacher{

// Provide construction method 
public Teacher() {

// stay No arguments structure Medium visit Parametric structure 
// this("jack");
System.out.println(" No arguments structure ");
}
public Teacher(String name) {

// stay Parametric structure Medium visit No arguments structure 
this();
System.out.println(" Parametric structure "+name);
}
}

2.4 Inherit

2.4.1 Concept

Inheritance is one of the most striking features of object orientation .

Inherit Is to derive a new class from an existing class , The new class can absorb the data properties and behaviors of existing classes , And can expand new capabilities .( Between classes )

Java Inherit It is the technology of building new classes based on the definition of existing classes , New class definition can add new data or new functions , You can also use the functions of the parent class , But you can't selectively inherit the parent class / Superclass / Base class .( Subclasses are also called derived classes )

advantage : This technique makes it very easy to reuse previous code , Can greatly shorten the development cycle , Reduce development costs .

example :

class A extends c{
 // The original eat() Take away 
}// Be careful : The grammar of inheritance , The second class doesn't need to be used anymore class
class B extends c{
 // The original eat() Take away 
}
class c{

public void eat(){

syso("eat");
}
}

2.4.2 characteristic

1、 Use extends keyword
2、 It is equivalent to that the subclass copies the function of the parent class ( Including variables and methods , Cannot be inherited , By creating objects, you can't change .)
3、java Only single inheritance is supported ( A superclass can have multiple derived classes , A derived class can only inherit one superclass )
4、 Inheritance can pass ( grandpa , son , Sun Tzu's relationship )
5、 Cannot inherit private members of a parent class
6、 Inheritance is often used to modify functions , A subclass can have the function of a parent at the same time , Expand the function
7、 yes is a The relationship between
8、java Regulations : A superclass must be constructed before a derived class can be constructed ( First a father had a son )
9、 Constructor cannot be inherited .

2.4.3 Introductory cases

package cn.tedu.extendsdemo;
// An introductory case for testing inheritance 
public class Test4_Extends {

public static void main(String[] args) {

// Create a parent object test , Improve code reusability / High cohesion , The commonness of the parent class and the child class 
Father f = new Father();
f.eat();
// System.out.println(f.sum);
// Create subclass object test 
Son s = new Son();
//5, The subclass can use all the functions of the parent class , except private Of 
s.eat();
// System.out.println(s.sum);
//6, Inheritance is transitive , Grandpa's function , It can also be used in grandchildren 
s.game();
System.out.println(s.count);
}
}
class Yeye{

int count ;
public void game() {

System.out.println(" play chess game ");
}
}
// Create parent class 
//!! Coupling -- Inheritance is a kind of strong coupling !!! The lower the coupling in the program, the better , Reduce program coupling . 888888888888888888888888( Interface for subsequent use )
class Father extends Yeye{

//4, If the parent class , Resources are private modification , This resource subclass cannot inherit 
private int sum =10;
public void eat() {

System.out.println(" Dad is eating pork ");
}
}
// Create subclass 
//1, use extends Keywords represent inheritance relationships 
//3,Java Only single inheritance is supported , A subclass can only inherit from one parent class 
class Son extends Father{

//2, After inheritance , Subclasses can use the functions of the parent class , It is equivalent to the subclass copying the function of the parent class 
} // Inheritance does not change the source code , It's about expanding 

2.4.4 Use of member variables

package cn.tedu.extendsdemo;
// Test the usage of member variables in inheritance 
// You can use... Inherited from the parent class , You can also use your own 
public class Test5_UseExtends {

public static void main(String[] args) {

//TODO Create subclass object test 
Erzi zi = new Erzi();
System.out.println(zi.count);//20
System.out.println(zi.sum);
}
}
// Create parent class 
class BaBa{

int count = 10;
}
// Create subclass 
class Erzi extends BaBa{

int count = 20;
int sum = 20;
}

2.4.5 Use of member methods

package cn.tedu.extendsdemo;
// Test the usage of member methods in inheritance 
public class Test5_UseExtends {

public static void main(String[] args) {

//TODO Create subclass object test 
Erzi zi = new Erzi();
// You can use the functions of the parent class , You can also use your own unique functions 
System.out.println(zi.count);//20
System.out.println(zi.sum);
//2, If the subclass does not have a method override ,eat() Use the functions of the parent class .
// If a subclass has a method override , What is used is after rewriting , That is, the subclass of eat() The function of .888888888888
zi.eat();// Dad is eating meat --》 My son is drinking soup 
zi.code();// Special methods can be used 
}
}
// Create parent class 
class BaBa{

int count = 10;
public void eat() {

System.out.println(" Dad is eating meat ");
}
}
// Create subclass 
class Erzi extends BaBa{

int count = 20;
int sum = 20;
//1, Method rewriting : The reason for this is : When the function of the parent class needs to be modified , We cannot directly open the parent code to modify the source code !! I can only expand the function 
// The process of expansion : Inheritance first , Then method rewriting occurs . As like as two peas, the method declaration of the subclass is exactly the same as the parent class. .
public void eat() {

System.out.println(count);//20
System.out.println(super.count);//10, adopt super Call the function of the parent class 
System.out.println(" My son is drinking soup ");
}
// Provide subclass specific methods 
public void code() {

System.out.println(" My son is typing the code ");
}
}

2.4.6 Use of construction methods ( Constructor cannot be inherited )

1、 When a subclass creates an object , By default, it will access the nonparametric constructor of the parent class
2、 In the first line of the constructor , There is a default statement :super();
3、 When the parent class has no parameterless construction , It can be used super Call other constructs of the parent class

package cn.tedu.extendsdemo;
// Test the use of construction methods in inheritance 
public class Test6_UseExtends2 {

public static void main(String[] args) {

//TODO Create subclass object test 
Zi zi = new Zi();
}
}
// Create parent class 
class Fu{

// If the parent class , Only parameter structures are provided , At this time , The nonparametric structure will be overwritten , be without !
// It is recommended to provide a parameterless structure .
public Fu(String n) {

System.out.println("Fu()...");
}
}
// Create subclass 
class Zi extends Fu{

public Zi() {

//0,super Keywords are often used in subclasses , When the subclass wants to use the function of the parent class , adopt super Represents a reference to a parent class object .
//1, When a subclass creates an object , The default will exist super(), By default, it will access the parameterless construction of the parent class .
// super();// The parent class has no parameterless structure !!
//2, When no parameterless construction is provided in the parent class , Only through super Call the parameterized constructor of the parent class 
//3,super Keywords if used in construction methods , Must be the first statement .
super("tony");
System.out.println("Zi()...");
}
}

2.5 super keyword

explain :
1、 adopt super Keywords can use the content of the parent class
2、super A reference object representing the parent class
3、 If used in the construction method , Must be the first statement

grammar :

1)super. Member variable name ------ Access the member variables of the superclass
2)super. Method name ()-------- Call the method of the superclass ------ Let's talk about it tomorrow
3)super()--------------- Call the constructor of the superclass

Be careful :

  1. super Can only appear in subclass methods or constructor methods .
  2. A subclass constructor can only have one super.
  3. super When constructing the parent class in the subclass construction method , Must be on the first line of the subclass constructor .( Common methods do not have this requirement )
  4. Even if it is not written, it is in the first line of the subclass constructor by default , To call the parameterless construction of the parent class . If the parent class overloads the class constructor , Its subclass super It needs to be called according to different parameters .
  5. In the construction method of subclass , You can call the constructor of the parent class , You can also call the normal methods of the parent class . Ordinary methods in a subclass can only call ordinary methods in the parent class , Cannot call constructor .

2.6 this And super The difference between

Different objects represented

  1. this: References representing objects of this class .
  2. super: Represents a reference to a parent class object .

Premise
3. this: You can use without inheritance .
4. super: Can only be used in inheritance conditions .

When a constructor is called :
5. this: The construction of this class
6. super: Construction of parent class

matters needing attention :this and super Cannot appear in the same construction method at the same time , Both of them have to be placed in the first line of the construction method whenever they appear , At the same time , Who's on the first line .

2.7 Method rewrite

Premise Occurs in a parent-child class .

Follow the principle of "two with two small and one"

 With two : Same method name , Same parameter list
Two small :
1: The return value type of the subclass is less than or equal to that of the parent class
1.1void And basic types , It has to be the same
1.2 When referencing a type : Less than or equal to the of the parent class
2: The exception thrown by the subclass is less than or equal to that of the parent class
A large : The access permission of the subclass is greater than or equal to that of the parent class

Be careful

  1. Rewriting refers to the rewriting of methods , Property has no override function ( Overloading is also ).
  2. The override method body can also be the same , Similar to overloading, but it doesn't make sense , It's usually different .
  3. Private methods in a parent class cannot be overridden , Because private cannot be inherited .
  4. static Method cannot be overridden , Belong to category , It's not an instance .
  5. final Methods that modify cannot be overridden .
  6. Constructor cannot be overridden .
  7. The identity of the override method is @Override annotation : There are specific small functions , This indicates that this method overrides the function of the parent class .

Why rewrite ???
When the function of the parent class , Subclasses need to be overridden when they do not need or do not necessarily meet .

2.7.1 Rewrite the introductory case

package cn.tedu.extendsdemo;
// Test the usage of member methods in inheritance 
public class Test5_UseExtends {

public static void main(String[] args) {

//TODO Create subclass object test 
Erzi zi = new Erzi();
// You can use the functions of the parent class , You can also use your own unique functions 
System.out.println(zi.count);//20
System.out.println(zi.sum);
//2, If the subclass does not have a method override ,eat() Use the functions of the parent class .
// If a subclass has a method override , What is used is after rewriting , That is, the subclass of eat() The function of .888888888888
zi.eat();// Dad is eating meat --》 My son is drinking soup 
zi.code();// Special methods can be used 
}
}
// Create parent class 
class BaBa{

int count = 10;
public void eat() {

System.out.println(" Dad is eating meat ");
}
}
// Create subclass 
class Erzi extends BaBa{

int count = 20;
int sum = 20;
//1, Method rewriting : The reason for this is : When the function of the parent class needs to be modified , We cannot directly open the parent code to modify the source code !! I can only expand the function 
// The process of expansion : Inheritance first , Then method rewriting occurs . As like as two peas, the method declaration of the subclass is exactly the same as the parent class. .
public void eat() {

System.out.println(count);//20
System.out.println(super.count);//10, adopt super Call the function of the parent class 
System.out.println(" My son is drinking soup ");
}
// Provide subclass specific methods 
public void code() {

System.out.println(" My son is typing the code ");
}
}

2.8 expand

2.8.1 The difference between rewriting and overloading (Overload and Override The difference between )

1、 heavy load : Multiple methods in the same class have the same name , But these methods have different parameter lists , That is, the number or type of parameters cannot be exactly the same
2、 rewrite : It exists between child and parent classes , A method defined by a subclass has the same method name as a method in a parent class , The same parameter table and the same return type
3、 Rewriting is a manifestation of polymorphism between parents and children
4、 Overloading is a manifestation of polymorphism in a class

2.8.2 Inherited memory structure

 Insert picture description here

3 Day08– object-oriented 3

3.1 static

3.1.1 Concept

1、 yes java One of the keywords in
2、 Used to modify member Member variables and member methods , Static code block ), Cannot decorate local resources .

3.1.2 characteristic

1、 You can modify member variables , Member method , Static code block .
2、 Load as class loads , Takes precedence over object loading
3、 Load only once , There will always be , No more new space
4、 Globally unique , Global Shared
5、 It can be called directly by the class name ( Static resources can be called through the class name point
6、 Static methods cannot be overridden .

Be careful Static attribute 、 Both static methods and non static properties can be inherited and hidden rather than overridden , Therefore, polymorphism cannot be realized , References that cannot implement a parent class can point to objects of different subclasses . Non static methods can be inherited and overridden , Therefore, polymorphism can be realized . Static methods and properties belong to classes , Call directly through the class name . The method name completes the call , You don't need inheritance mechanism and can call .

problem : Static can only call static , Non static can call static and non static , Why? ?
because : Static resources are loaded with classes , Takes precedence over object loading , When the class is loaded, the object has not been created , So you can't call .
Empathy static Unable to join this perhaps super share :this,super Instead of the object , Yes static There may be no object yet ,main Methods are also static methods, so don't write this,super.

Call relationship summary
Calls between the same class do not need to create objects , Resources between different classes are called by creating objects or using static resources .
Non static resources ( Instance variables and common methods , Excluding local variables , Because if you want to call a local variable, you have to call the method first ) Can only be used by creating objects , Static resources ( Static variables and static methods ) You can create objects or class names . Call directly ( Static resources are recommended to use the class name to call ).

3.1.3 practice 1: Introductory cases


package cn.tedu.staticdemo;
//static Usually placed before the return value . 
// This class is used to test static entry cases 
public class Test1_Static {

public static void main(String[] args) {

//2, Static resources take precedence over object loading , Will be preferentially loaded into memory 
// Static resource access : Yes 2 Kind of . There can only be one non static resource : Through object 
//1: adopt new Object to access ·( But it's not recommended )
//2: Directly by class name . visit 
Person.game();
System.out.println(Person.age);
//TODO establish Person Object test 
Person p = new Person();
p.eat();
System.out.println(p.name);
//1.1, Static resources , Can be accessed through objects 
p.game();
System.out.println(p.age);
//1, Static resources , You can also access... By class name 
Person.game();
System.out.println(Person.age);
//3, Static resources , Between multiple objects , Is Shared 
Person p1 = new Person();
Person p2 = new Person();
p1.age=10;
System.out.println(p2.age);//10
}
}
// establish Person class 
class Person{

// General resources 
String name;
public void eat() {

System.out.println("eat()...");
}
// Static resources -- Use static modification 
static int age;
static public void game () {

System.out.println("game()...");
}
}

3.1.4 Static method memory graph

 Insert picture description here

Memory : from JVM Managed
1. Pile up : all new Out object ( Include new The object and member variables )
2. Stack : local variable ( Include method parameters Values of basic types Address of reference type )
3. Method area :.class Bytecode file ( Including method )

3.1.5 practice 2: Static call relationship

Static can only be adjusted , Non static can be called arbitrarily !!!

 package cc;
// establish Student class 
class Student {

// General resources 
static String name ;
public void study() {

//1, General resources call Static resources Is that OK ?? --- Sure 
coding() ;
System.out.println("study()...");
}
// Static resources 
static double score ;
static public void coding() {

//2, Static resources call General resources Is that OK ?? --- Can not be !!! Because static can only call static 
// study() ;
// System.out.println(this.name);//3,Cannot use this in a static context
// System.out.println(super.);//4, Static resources are loaded into memory prior to objects . Objects are later produced , There will be cases where non-existent objects are loaded , Not allowed 
System.out.println("coding()...");
}
}

3.2 Static code block

3.2.1 Static code block

Load as class loads , And it's loaded only once , It is generally used for project initialization

static{
}

3.2.2 summary

1、 Static code block : Load when the class is loaded , And only be loaded ( call ) once , It is generally used for project initialization .
2、 Location : Inside the class, outside the method
3、 Static code block :static{

3.2.3 Test static , structure , Local code block loading order

The order of execution is Static code blocks are the fastest , Because it is called automatically when the class is loaded , And only called once, followed by the construction of code blocks , Construction method , Local code is fast .

package cn.tedu.block;
// Test code block 
// summary :
//1, Trigger time node : When calling a method , Will enter the category first , Then the static block will be called automatically ( namely , When the class is first loaded )
//2, Location : In class , Outside method 
//3, effect / function : Used when loaded only once .
// The order of execution is : Static code blocks are the fastest , Because it is called automatically when the class is loaded , And only called once, followed by the construction of code blocks , Construction method , Local code is fast .
public class Test3_Block {

public static void main(String[] args) {

//TODO Create object test 
TestBlock tb = new TestBlock();
tb.show();// Trigger local code blocks 
TestBlock tb2 = new TestBlock();
}
}
// establish TestBlock class 
class TestBlock{

//1, Provide construction code blocks 
{

System.out.println(" Building blocks of code ");
}
//2, Provide static code blocks : Load early , And it only loads once 
static{

System.out.println(" Static code block ");
}
//3, Provide construction method 
public TestBlock() {

System.out.println(" Construction method ");
}
//4, Provide local code blocks 
public void show() {

{

System.out.println(" Local code block ");
}
}
}

3.2.4 summary : Static code block , Building blocks of code , Local code block

Static code block static{ }: Load when the class is loaded , And it's loaded only once , It is generally used for project initialization , Inside the class, outside the method .

Building blocks of code { }: Called automatically when an object is created , Every time you create an object, it's called , It is usually used to extract common code in construction methods , Inside the class, outside the method .

Local code block { }: When a method is called, call , The scope of action used to control variables , In the method .

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

  1. If some code has to be executed at the start of the project , You need to use static code blocks , This kind of code is active ;
  2. If you need to initialize when the project starts , Without creating objects , When other programs call , You need to use static methods , This kind of code is executed passively . Static methods are loaded when the class is loaded , You can call... Directly with the class name . such as :main Methods have to be static , This is the program entry .

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

3.3 final

3.3.1 Concept

  1. yes java A keyword provided .
  2. final Is the ultimate meaning .
  3. final Modifiable class , Method , Variable , member All parts are OK .

The original intention is because java After the emergence of inheritance , The subclass can change the function of the parent class , It can be used when the function of the parent class does not allow the change of the child class final Keyword modifies the parent class .

3.3.2 characteristic

  1. By final Modified class , uninheritable ( benefits : The point of making a class not inheritable is : It can protect the class from inheritance and modification , We can control the harm of abusing inheritance to the system )
  2. By final The method of decoration , Can't be rewritten , But it can overload
  3. By final The modified variable is a constant , Value cannot be changed

Be careful :final When modifying a variable of reference type, it means that the reference cannot be changed , As for the properties of the object, you can change them at will .

The definition form of constant final data type Constant names = value ;, Generally, in order to facilitate external calls , Will be static modification , Can be directly by class name . visit . The final form is :public final data type Constant names = value ;.

Constant naming conventions It is recommended that all letters of constant names be capitalized , Underline multiple words ("_") separate ( Recommendation is not mandatory )
Constant considerations :

  1. Must declare and initialize at the same time ( The initial value must be assigned directly , Do not modify ),( Assignment in static blocks can also , But it is not recommended. )
  2. Accessed by the class name point , And can't change

Advantages of constants : Constants are directly replaced with specific values at compile time - - Efficient

When constants are used ? Data is always constant and often used .

3.3.3 Introductory cases

package cn.tedu.finaldemo;
// test final keyword 
//1、 By final Modified class , uninheritable 
//2、 By final The method of decoration , Can't be rewritten 
//3、 By final Decorated variable , It's a constant , Value cannot be changed 
//4、 The definition form of constant :final data type Constant names = value 
public class Test4_Final {

public static void main(String[] args) {

Sub s = new Sub();
// The final field Sub.sum cannot be assigned
// s.sum = 20;
System.out.println(s.sum);
}
}
// Create parent class 
//The type Sub cannot subclass the final class Father
//final class Father{

class Father {

//Cannot override the final method from Father
final public void eat() {

System.out.println("Father..eat()");
}
}
// Create subclass 
class Sub extends Father {

final int sum = 10;
}

3.4 polymorphic

3.4.1 Concept

Polymorphism means that the same entity has multiple forms at the same time . It's object-oriented programming (OOP) An important feature of . It mainly refers to the same object , At different times , They represent different objects , It refers to various forms of objects .

benefits : You can treat different subclass objects as parent classes , You can mask the differences between different subclass objects , Write common code , Make general programming . Unified calling standard , The standard is the parent class .

for example
water , There can be many forms at different times , Including steam , ice , water .
Java How to embody polymorphism ? Dogs come in two forms : Dogs and small animals

class Animal {

public void eat(){

}
}
class Dog extends Animal{

}
class Test1{

main(){

// Create subclass objects 
Dog d = new Dog();// A dog is a dog 
// Creating polymorphic object tests 
Animal a = new Dog();// Dogs are small animals ( If it is a parent type, it is polymorphic )
// Parent class reference , Point to Subclass object 
// compile ctrl+s Look to the left , function ctrl+f11 Look to the right 
}
}

3.4.2 characteristic

1、 The premise of polymorphism 1:2 A class has an inheritance relationship
2、 The premise of polymorphism 2: There should be method rewriting
3、 Polymorphism refers to the polymorphism of a method , Property is not polymorphic
4、 The parent class reference points to the subclass object , Such as :Animal a = new Dog(); - - Big to small , Turn up ( build ) type
5、 In polymorphism , Compile to the left , Run to the right
The code we write is the source file ctrl +s Will automatically .java The file is compiled as .class Bytecode file .
 Insert picture description here

3.4.3 Introductory cases

package cn.tedu.duotai;
// An introduction to testing polymorphism 
public class Test5_Duotai {

public static void main(String[] args) {

//TODO Create a parent object test 
Animal a = new Animal();a.eat();// Is to use the functions of the parent class itself 
//TODO Create subclass object test 
Dog d = new Dog();d.eat();// Before rewriting , Use the parent's . After rewriting , The execution is the subclass .
//TODO Creating polymorphic object tests 
Animal an = new Dog();// formula 1: Parent class reference Point to Subclass object 
// formula 2: Compile to the left , Run to the right 
// Compile to the left : Want to be able to save successfully , Only the method declaration part provided by the parent class on the left can be used 
// Run to the right : It means that after rewriting , The execution result is subject to the subclass 
an.eat();// Called the method declaration of the parent class , The method body of the overriding parent method of the output subclass . 888888888888888
// Polymorphism is mainly used to unify the calling standard : All method calls are aligned with the parent class 
}
}
//1, The premise of polymorphism : Inherit + rewrite 
// Create parent class 
class Animal{

public void eat() {

System.out.println(" Dad is eating meat ");
}
}
// Create subclass 
class Dog extends Animal{

@Override // It checks whether method overrides have been written ,2 The one who appears together 
public void eat() {

System.out.println(" My son is drinking soup ");
}
// Subclass specific methods , Polymorphic objects cannot call !!!! Want to use , You can create subclass objects with 
public void eat2() {

System.out.println(" My son is drinking soup ");
}
}

3.5 The benefits of polymorphism

  1. Polymorphism allows us not to care about the exact type of an object , You can use some methods of the object .
  2. It improves the expansibility and maintainability of the program

The code is :

 class Animal{

//Object It's a manifestation of polymorphism , Don't care who the specific subclass is , As long as it is Object Subclasses of can be received as parameters .
// Write common code , Look at all subclasses as parent classes .
public void eat(Object a){

}
}
class Dog extends Animal{
// Teacher's notes 
}
class Cat extends Animal{

}
class Tiger extends Animal{

}
class Test{

eat(Animal a){
}// polymorphic , Don't care about specific subclass types , Will treat the subclass as the parent class 
//eat(Dog d){}
//eat(Cat c){}
//eat(Tiger c){}
...
}

3.5.1 characteristic

1、 Member variables : Using the parent class
2、 Member method : Due to the rewriting phenomenon, the subclass is used
3、 Static members : Exist with objects , Whoever invokes it will return its
4、 Static methods : Can be inherited and hidden, but cannot be overridden , Therefore, polymorphism cannot be realized .

Be careful

  1. Variable does not exist , Polymorphic calls are all resources of the parent class , But if the method is overridden, the declaration of the parent class is called , Method body of subclass .
  2. pereson p = new Son(); What can be called is always related to the left of the equal sign , It has nothing to do with the right .

3.5.2 test

package cn.tedu.duotai;
// Test the use of polymorphism 
public class Test6_UseDuotai {

public static void main(String[] args) {

//TODO Creating polymorphic object tests 
Fu fu = new Zi();// Look up 
//1, In polymorphism , The parent variable of . Because look at the left , The default call is provided by the parent class count
System.out.println(fu.count);
//2, In polymorphism , Who called the member's method ???-- The method declaration calls the of the parent class , Method body exists , So the method body of subclass is used 
fu.eat();
//3, Does polymorphism unify the standard of call ?? -- Can only call Parent class Features provided 
fu.show();
// fu.test();//test() Is a subclass specific method , Does not meet the polymorphic call criteria 
//4, Just want to use subclass specific methods test(), You can only create subclass objects to access or shape down 
Zi zi = new Zi();zi.test();
//5, In polymorphism , Whose static resources are used ??? --- Use whoever calls it ,fu Is the parent type , It is equivalent to calling the resources of the parent class , It goes with static No problem .
System.out.println(fu.name);
}
}
//7. Static resource does not exist ( Variables do not override properties , Only methods have overridden properties ). Polymorphic calls are always the resources of the parent class 
f.he();
// The premise of polymorphism : Inherit + rewrite 
// Create parent class 
class Fu{

int count = 10;
// Provide static resources 
static String name="jack";
// Provide member methods 
public void eat() {

System.out.println("Fu...eat()");
}
public void show() {

System.out.println("Fu...show()");
}
}
// Create subclass 
class Zi extends Fu{

int count = 20;
// Provide static resources 
static String name="rose";
@Override
public void eat() {

System.out.println("Zi...eat()");
}
public void test() {

System.out.println("Zi...test()");
}
}

3.6 instance of

effect : Determine whether the object is an instance of this specific class or its subclass .

package com.shuai;
public class Demo03 {

public static void main(String[] args) {

//Object>Person>Student
//Object>Person>Teacher
//Object>String
Object obj = new Student();// use Object receive , be in Object Level .
// Understand that the current object refers to obj, It can be seen as Student. Take it Student It's easy to understand by comparison .
//System.out.println(x instanceof Y); Whether it can be compiled depends on X Whether it is Y Subclasses of .
System.out.println(obj instanceof Student);//true The current object is Student An example of , So for true
System.out.println(obj instanceof Person);//true The current object is Person A subclass of , So for true
System.out.println(obj instanceof Object);//true The current object is Object A subclass of , So for true
System.out.println(obj instanceof Teacher);//false The current object obj yes Student type , It can be seen as Student.Student and Teacher It doesn't matter. , So for false
System.out.println(obj instanceof String);//false Ibid false
System.out.println("****************");
Person person = new Student(); // use Person receive , be in person Level 
System.out.println(person instanceof Student);//true
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Object);//true
System.out.println(person instanceof Teacher);//false There is an indirect relationship 
//System.out.println(person instanceof String); Compiler error Because the Student The object is person Received , At the second level , and Teacher It doesn't matter. , There is no indirect relationship .
System.out.println("****************");
Student student = new Student();// use Student receive , be in Student Level 
System.out.println(student instanceof Student);//true
System.out.println(student instanceof Person);//true
System.out.println(student instanceof Object);//true
//System.out.println(student instanceof Teacher); Compiler error There is no indirect relationship 
//System.out.println(student instanceof String); Compiler error There is no indirect relationship 
}
}
class Person{

}
class Student extends Person{

}
class Teacher extends Person{

}

3.7 Type conversion ( Look up / Shape down )

explain

  1. It can only be the reference of the parent class pointing to objects like .
  2. Look up : Automatic conversion
  3. Shape down : A strong turn is needed ( Rarely used )
  4. java Think super class is big , Derived class small .
  5. java The strong conversion of the basic type in will not report an error , But the successful conversion of reference type is only 2 Kind of
  6. Converting a subclass into a parent class may lose some of its original methods .

Cast ( Shape down ), There are only two conditions for success :

  1. Reference to the object , That's the type ( The object pointed to by the reference refers to The object referred to by the reference in the upward modeling , Compare it with the one in the downward shape bracket .)
  2. Reference to the object , Implements the interface or inherits the class

Suggest : If the above conditions are not met during forced rotation , Then ClassCastException Type conversion exception . Usually pass... Before strong turn instanceof( The result is true or false) To determine whether the object pointed to by the reference is of this type .

package com.shuai;
public class Demo04 {

public static void main(String[] args) {

// Conversion between types : Similar to basic type conversion Father ( high ) Son ( low )
// high low 
Person1 person1 = new Student1();// Look up 
//person1.go(); Report errors , There are no subclass specific methods in the parent class , Unable to call 
// solve : take person1 Turn into Student1 type , You can use it 
Student1 ss = (Student1) person1; // Shape down : Want to use subclass specific methods .
ss.go();
//2 Write the sentence in one piece :((Student1) person1).go(); You need to write more parentheses 
}
}
class Person1{

public void run(){

System.out.println(" Output run Method ");
}
}
class Student1 extends Person1{

public void go(){

System.out.println(" Output go Method ");
}
}

3.8 expand

3.8.1 Differences between static variables and instance variables

Differences in grammatical definitions : Add before static variable static keyword , Instance variables are not added before .

Differences in program runtime : Instance variable belongs to an object's property , Instance object must be created , The instance variables will be allocated space , To use this instance variable . Static variable does not belong to an instance object , It's a class , So it's also called class variable , As long as the program loads the bytecode of the class , Do not create any instance objects , Static variables are allocated space , Static variables can be used , Of course, you can also .

All in all , Instance variables must only be used by creating objects , Static variables can be created by objects or by class names . Call directly ( Static variables are recommended to use the class name to call ).

4 Day09– object-oriented 4

4.1 Access control character

To control a class , perhaps Member variables in class , Method Access scope of .( Cannot be used for local variables )

class package Subclass arbitrarily
public
protected
default
private

explain

  1. public: Open , Any class , Anywhere in the same project
  2. protected: The protected , This category 、 Derived class 、 Same as the package //protect You can use subclasses from other packages
  3. default : Write nothing , This category 、 Same as the package ( Classes in the same package ), But you can't put default Write out
  4. private: Private , This category

Be careful

  1. Modifiers like this public,protected,default,private,static,final,abstract Do not prioritize , For example, decorating methods only need to be in the return value type .
  2. The access modifier of a class can only be the default or public( There can only be one and the class name …)
  3. Members of class ( Variable , Method ) The access modifier of is as above 4 All kinds
  4. Get used to general data ( Member variables ) Privatization (private) Behavior ( Method ) Into the open (public)) .
  5. If it is the parent class in the inheritance relationship , Inside is permission, at least protected, Because to use its derived class, you need to call the parent resource .

4.2 abstract class

4.2.1 Concept

Java Methods without method bodies can be defined in , This method is implemented by its subclasses . The Methods without method bodies are called abstract methods , Classes that contain abstract methods are called abstract classes .
Abstract class can be understood as a special class with only method declaration and no method body .

The formula :

// Abstract method , There is no method body , There are no braces , There is one ”;”.
Modifier abstract return type Method name ( parameter list );

The meaning of abstract class : You can extract the commonness of the code , Subclass inheritance for extension , Improve code development efficiency .

give an example : Fruits , thing ..


class A{

public void eat(){
// The statement is the same , Can be extracted 
syso("eat...B") }
}
class B{

public void eat(){
// The statement is the same , Can be extracted 
syso("eat…A") }
}
abstract class C{

public abstract void eat();
}

4.2.2 characteristic

  1. adopt java keyword abstract Realization .
  2. Can be modified Method or class .
  3. A class containing an image extraction method must be an abstract class , Abstract classes do not necessarily contain abstract methods ( Because it can be implemented by subclasses ).
  4. There can be no abstract methods in an abstract class ( By subclasses ), There can be abstract methods , There can also be common methods , There must be Construction method ( Used for subclass instantiation ), There can be Member variables , Constant .
  5. If there are abstract methods in the class , Then the class must be defined as an abstract class .
  6. After subclasses inherit abstract classes ,(1) Or it's still an abstract class ,(2) Or override all the abstract methods of the parent class .
  7. It's mostly used in polymorphism .
  8. Abstract classes cannot be new Instantiate an object, but you can new Array .

Why do abstract classes have construction methods If not, your subclass will not compile , Because the first statement in any constructor implicitly calls super().

summary : Situations that cannot occur at the same time 888888888888
9. final and abstract Can't appear at the same time because fianl Is fixed and cannot be inherited , and
abstract Generally not used alone , Use with derived classes
2.this and super It can't be used together , Because the construction methods are in the first line
3.static and this super Not at the same time , Because there is static The object has not been created yet .(main Methods are also static methods, so there can be no this,super)
Be careful : Modifier final static abstract Almost all of them void Written before

4.2.3 Introductory cases

 package cn.tedu.abstractdemo;
// An introductory case for testing abstract classes 
public class Test1_Abstract {

public static void main(String[] args) {

//TODO Creating polymorphic object tests 
//7, Abstract class cannot be instantiated new So we can use polymorphic instances to the objects of its ordinary subclasses 
// Animal a = new Dog();
Animal a = new Cat();
a.eat();// Dogs eat meat 
}
}
// Create parent class 
//3, If there are abstract methods in the class , This must be declared as an abstract class 
abstract class Animal{

//1, The methods provided by the parent class , If the subclass needs to be changed , The change is the method body , But the method statement is required not to be changed !!!( And : Method body without parent class , Even cover it , The method body that can not write the parent class is an abstract method )
// At this time , Can we just provide method declarations , No method body is provided -- Sure , At this time, the method has no method body , Called abstract methods 
//2, adopt abstract To make it abstract 
abstract public void eat() ;
//4, Provide another abstract method and Common method 
abstract public void game();
public void chiji() {

System.out.println(" Eating chicken ");
}
}
// Create subclass 
//5, After subclass inherits abstraction , Subclasses can put all abstract methods Rewrite it all , That's an ordinary subclass 
class Cat extends Animal{

// Rewrite all abstract methods 
// annotation :1, Indicates that a method override has occurred 2. Checking out this place must result in rewriting , Only if this annotation is not written, an error will be reported 
@Override // Shortcut key @ alt+ /
// It can also be direct , Overridden method name +alt+/
public void eat() {

System.out.println(" Cats eat fish ");
}
@Override
public void game() {

System.out.println(" Play with wool ");
}
}
//6, After subclass inherits abstraction , Not all abstract methods Rewrite it all , That is an abstract subclass 
abstract class Dog extends Animal{

// Override abstract methods 
@Override
public void eat() {

System.out.println(" Dogs eat meat ");
}
}

4.3 Usage of abstract classes

4.3.1 Construction method

Abstract classes also have construction methods , But it cannot instantiate itself .
What's the use of the constructor of that abstract class
Generally used to instantiate subclasses .( Because subclasses have super Call the parent class constructor by default .)

package cn.tedu.abstractdemo;
// Test the usage of abstract class constructor 
public class Test2_UseAbstract {

public static void main(String[] args) {

//3, Abstract class cannot be instantiated , What's the use of providing construction methods ??-- Used to create subclass objects .
// as a result of : When a subclass creates an object , There will be a default in the constructor super()
// Animal2 a = new Animal2();
//TODO Creating polymorphic object tests 
Animal2 a = new Dog2();
}
}
// Create parent class 
abstract class Animal2{

//1, There can be construction methods -- effect : Used to create objects 
public Animal2() {
 // It's best to manually provide a parameterless construct 
System.out.println("Animal2()...");
}
}
// Create subclass 
class Dog2 extends Animal2{

public Dog2() {

super();//2, Default exists , The constructor of the parent class will be called automatically 
System.out.println("Dog2()...");
}
}

4.3.2 Member variables and constants of abstract classes

You can have variables , You can also have constants .

package cn.tedu.abstractdemo;
// Test the usage of member variables and constants of abstract classes 
public class Test2_UseAbstract {

public static void main(String[] args) {

//3, Abstract class cannot be instantiated , What's the use of providing construction methods ??-- Used to create subclass objects .88888888888888888
// as a result of : When a subclass creates an object , There will be a default in the constructor super()
// Animal2 a = new Animal2();
//TODO Creating polymorphic object tests 
Animal2 a = new Dog2();
System.out.println(a.sum);//10
System.out.println(a.NAME);//xiongda
System.out.println(Animal2.NAME);//xiongda
}
}
// Create parent class 
abstract class Animal2{

//a, Abstract classes can provide member variables 
int sum = 10;
//b, Abstract classes can provide member constants 
static final String NAME="xiongda";
//1, Provide construction method -- effect : Used to create objects 
public Animal2() {

System.out.println("Animal2()...");
}
}
// Create subclass 
class Dog2 extends Animal2{

public Dog2() {

super();//2, Default exists , The constructor of the parent class will be called automatically 
System.out.println("Dog2()...");
}
}

4.3.3 Member methods of abstract classes

  1. In abstract class , There can be common methods , There can be abstract methods .
  2. Can all abstract classes be ordinary methods ? – Sure
  3. If there are ordinary methods in abstract classes , Why should it be decorated as an abstract class ?— Don't let the outside world new( Don't let the outside world instantiate objects )
  4. Are there any abstract methods in the ordinary class ? – Sure
  5. Can abstract classes be instantiated ? – Can not be
  6. Abstract class is a special class , Where is the special ? – Can contain abstract methods
  7. How to decide , Are ordinary methods or abstract methods provided for abstract classes ?– See if you want to give the method body
  8. test :

package cn.tedu.oop;
// test abstract class Member method 
public class Test1_UseAbstract {

public static void main(String[] args) {

// Creating polymorphic object tests 
Fu fu = new Zi();
fu.eat();
fu.sleep();
fu.game();
}
}
//2, If the class contains abstract methods , that , This class must be modified to abstract class 
//3, Abstract class is a special class , More flexible . Special in : Abstract classes can have abstract methods , There can also be common methods .
// Is it an ordinary method or an abstract method , See if you want to provide a method body .
abstract class Fu{

//4, This method is the final method , Can't be overridden by subclass !!
final public void eat() {

System.out.println(" Dad is eating meat ");
}
//1 , sleep Inherited by subclasses , And method rewriting happened , That is, you want to change the method body of the parent class .--- The parent class does not provide the method body , It becomes an abstract method 
abstract public void sleep() ;
abstract public void game() ;
}
//5 , After the subclass inherits the abstract class , Sure Rewrite all abstract methods , otherwise , Subclass contains abstract method, which is an abstract subclass 
class Zi extends Fu{

@Override
public void sleep() {

System.out.println("Zi...sleep()");
}
@Override
public void game() {

System.out.println("Zi...game()");
}
}

4.4 The way of not letting the outside world instantiate objects (2 Kind of )

  1. Modify your class into an abstract class
  2. Privatize your construction methods

4.5 How to assign values to member variables (2 Kind of )

1. call setXxx()
2. Assign value by construction method ( When you create an object, you call the constructor , In the construction method, the value passed from the property is paid to the member variable )

reason The reason for not assigning values directly is that the code is inflexible when it is written dead .

5 Day10– object-oriented 5

5.1 Interface (default New characteristics )

5.1.1 Concept

Java Because multiple inheritance is not allowed , So if you want to implement the functions of multiple classes , It can be implemented by implementing multiple interfaces .
Java Interface and Java abstract class It stands for abstract type , It is the concrete representation of the abstraction layer that we need to put forward .OOP object-oriented Programming for , If you want to improve the reuse rate of the program , Increase the maintainability of the program , Extensibility , It has to be interface oriented programming , Abstract oriented programming , Use the interface correctly 、 Abstract class these too useful abstract types are used as java At the top of the hierarchy .

grammar :

interface The interface name {

Code …
}
abstract class Class name {

Code …
} //2 The word becomes a 

5.1.2 characteristic

  1. The methods in the interface are all public abstract methods , Variables are public constants , There is no way to construct ( The resources in the interface are public ).
  2. adopt interface keyword Create an interface
  3. adopt implements Let the subclass implement Abstract classes are extends Inherit
  4. Can be interpreted as , Interface is a special abstract class
  5. The interface broke through java The limitations of the single inheritance
  6. Interface and class can be implemented more , Interface and interface can inherit more (“,” separate ), It can also inherit and implement more at the same time , But it can't inherit more than one implementation at the same time or Change the order, implement the inheritance first .( summary : There is inheritance between the same types , The difference is to realize the relationship .)
  7. Interface is the rule of exposure , It's a set of development specifications
  8. The interface improves the function extension of the program , Reduced coupling ( Coupling is the relevance of the program , The lower the relevance, the better )

Be careful

  1. The interface inherits how the interface is called ? Because the interface is a special abstract class, it cannot be instantiated , So we can only create an ordinary subclass to implement this interface , When instantiating this implementation class .
  2. it is to be noted that Override the permissions of abstract methods in the interface , Because the default is public So the permission of the subclass is at least equal to public(2 Same as 2 The small one principle ).
  3. Interface default New characteristics : jdk from 1.8 There can be common methods in the start interface , use static Or by default default modification .
  4. The interface has the meaning of ordinary methods : If an abstract class has many abstract methods, it's too troublesome to rewrite subclasses , It's easy to rewrite if you want to rewrite it in the ordinary way .

5.1.3 Introductory cases

 package cn.tedu.interfacedemo;
// Introduction case of interface 
public class Test4_Inter {

public static void main(String[] args) {

//TODO Creating polymorphic object tests 
//5, Can interfaces create objects ??? --- You can't !!! Just like an abstract class , Can't instantiate 
// Inter i = new Inter();
Inter i = new InterImpl();
i.delete();
i.save();
}
}
// Create an interface 
//1, adopt interface Keyword definition interface 
interface Inter{

//2, Can there be common methods in the interface ???--- Can not be !!! Methods are abstract 
abstract public void delete();
abstract public void save();
}
//3, Implementation class , Want to use the functions in the interface , need Realization Interface , use implements keyword 
//4, After the implementation class implements the interface , It can be a common implementation class , It requires rewriting all abstract methods 
class InterImpl implements Inter{

// Rewrite all abstract methods ( Note that abstract methods have semicolons , There is no method body , even {} either )
// The rewritten method turns it into an ordinary method , hold abstract Get rid of , Writing style , Pay attention to the semicolon .
@Override
public void delete() {

System.out.println("delete()...");
}
@Override
public void save() {

System.out.println("save()...");
}
}
// Implementation classes usually add... To the interface Impl
//6, After the implementation class implements the interface , If you don't rewrite all the abstract methods , Is an abstract subclass 
abstract class InterImpl2 implements Inter{

}

5.2 Usage of interface

5.2.1 Construction method

There is no constructor in the interface , Default when creating objects that implement classes super(), Is the default of the call Object The nonparametric structure of .

public interface Inter2 {

// Can there be a constructor in the interface ???-- No, !!, Abstract classes have 
// public Inter2() {}
}

5.2.2 Member variables

  1. The resources in the interface are public , use public modification .
  2. Interface variables The default is static constants .
  3. summary : The variables in the interface are Public static state Constant .

example :


public static final int age;
Equivalent to :
int age; // The interface will be spliced automatically by default public static final

5.2.3 Member methods of the interface

  1. The resources in the interface are public , use public modification .
  2. Methods in the interface , The default is abstraction Of , Even if you don't write, it will be spliced by default , It just doesn't show .
  3. summary : The methods in the interface are Public abstract Method , Even if you don't write, it will be spliced by default , It just doesn't show .

example :

public abstract void save();
Equivalent to :
void save(); // It will be spliced by default public abstract 

5.3 Complex use of interfaces

Java The limitation of Zhongshan inheritance can be solved through the interface : Interfaces can be inherited or implemented in many ways , You can even inherit and implement more at the same time .

package cn.tedu.interfacedemo;
// This class is used to test the complex usage of the interface : More inheritance, more implementation 
public class Test4_ComInter {

public static void main(String[] args) {

Interface1 in = new Interface1Impl();
in.save();
in.update();
}
}
// Create an interface 1
interface Interface1{

void save();
void update();
}
// Create an interface 2
interface Interface2{

void get();
void delete();
}
//1、 To break the java Limitations of single inheritance , Because interfaces can inherit more , Multiple interfaces are separated by commas 
interface Interface3 extends Interface1,Interface2{

void add();
}
//3、 Can I implement more interfaces ??--- It can be realized more , It's just that the interfaces are separated by commas 
class ManyImpl implements Interface1,Interface2{

public void save() {
}
public void update() {
}
public void get() {
}
public void delete() {
}
}
//4、 Interfaces can be inherited at the same time , Multiple implementation ?? -- 
class MoreImple extends ManyImpl implements Interface1,Interface2 {

}// Be careful : You can only inherit first and implement in multiple . Order cannot be changed , And you can't inherit and implement more .
//2、 Create implementation classes , Use 3 The function of interface No , How many methods need to be rewritten ??--- And rewrite 1 Number and 2 Number and 3 All functions in No. 1 interface 
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 Create implementation classes 
class Interface1Impl implements Interface1{

@Override
public void save() {

System.out.println("save()...");
}
@Override
public void update() {

System.out.println("update()...");
}
}

5.4 I'm new to design patterns

Java There is 23 Design patterns , The essence is the practical application of object-oriented design principles , It's encapsulation of classes 、 Inheritance and polymorphism , And a full understanding of the association and composition of classes .
Of course , Software design pattern is just a guide , In actual software development , You have to choose according to your specific needs .
1、 For simple programs , It may be easier to write a simple algorithm than to introduce a design pattern .
2、 But for large project development or framework design , It's obviously better to organize your code with design patterns .

5.4.1 Singleton design pattern concept

Singleton pattern can be said to be the most used in practice by most developers , common Spring Created by default bean It's in singleton mode .
Singleton mode has many advantages , For example, it can save system memory space , Control the use of resources .
The most important thing in singleton mode is to ensure that there is only one object .
Simply speaking , To ensure that a class has only one object in memory .
RunTime It is a typical single case design , We pass the right RunTime Class analysis , Take a look at it .

5.4.2 Source 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、 Create static globally unique objects 
private static Runtime currentRuntime = new Runtime();
//2、 Private constructor , 
/** Don't let anyone else instantiate this class */
private Runtime() {
}
//3、 Get the instance through a custom static method 
public static Runtime getRuntime() {

return currentRuntime;
}
}

5.4.3 Hungry Chinese style

Purpose : Controlling the number of objects created by the outside world can only create 1 Objects .
Development steps :
1、 Privatized construction method
2、 Create an object inside the class
3、 Provide a public get(), Returns a ready object

package cn.tedu.single;
// Test the singleton design pattern 
public class Test8_Single {

public static void main(String[] args) {

Single s = Single.get();
Single s1 = Single.get();
//get() How many times , The same object is used in memory 
System.out.println(s);//[email protected]
System.out.println(s1);//[email protected]
}
}
class Single{

// 1、 Privatized construction method , Don't let the outside world directly new
private Single() {
}
// 2、 Inside the class , Create the object 
//static : Static can only call static 
static private Single s = new Single();
// 3、 Provide a public get(), Returns a ready object 
//static It is for the outside world to access the method directly through the class name instead of through the object 
static public Single get(){

// Be careful : Static can only call static 
return s;
}
}

5.4.4 Slacker type

class Single{

// 1、 Privatized construction method , Don't let the outside world directly new
private Single() {
}
// 2、 Inside the class , Create the object 
//static : Static can only call static 
static private Single s = null;
// 3、 Provide a public get(), Returns a ready object 
//static It is for the outside world to access the method directly through the class name instead of through the object 
synchronized static public Single get(){

// Be careful : Static can only call static 
if(s==null){

s = new Single();// There will be security issues 
}
return s;
}
}

summary : The difference between the hungry and the lazy :
1、 Starved Chinese is thread safe , When creating a class, a static object has been created for the system to use , I don't want to bai Changing . Lazy if you don't add synchronized This will result in access to objects that are not thread safe .

2、 In terms of implementation, the biggest difference between them is that lazy loading is delayed loading , He creates objects when needed , The hungry man style will be created when the virtual machine starts , Hungry Han style does not need to pay attention to multithreading , The writing is simple and clear , If you can use it, you can use it . The singleton object is created only when it is actually used ,“ Hungry Chinese style ” Whether it's used or not , Create this singleton object from the beginning .

5.6 expand

5.6.1 abstract matters needing attention

Abstract methods must be overridden after subclass inheritance . that ,abstract Which keywords can't be used with ? The following keywords , In an abstract class , It can be used , It just doesn't make sense .
1、private: After being privatized , Subclass cannot override , And abstract Contrary to .
2、static: Static , Prior to the existence of objects . Abstract methods need subclass rewriting , Static methods cannot be overridden , So they are contradictory .
3、final: By final After modification , Can't rewrite , And abstract Contrary to .

5.6.2 The difference between interface and abstract class

1、 Abstract classes and interfaces cannot be instantiated directly , If you want to instantiate , Abstract class variables must point to subclass objects that implement all abstract methods , Interface variables must point to class objects that implement all interface methods .
2、 Abstract class should be inherited by subclass , Interface to be implemented by class .
3、 Interfaces can only make method statements , Method declaration can be made in abstract classes , It can also be realized by methods
4、 The variables defined in the interface can only be public static constants , Variables in an abstract class are ordinary variables .
5、 Abstract methods in abstract classes must be implemented by subclasses , If the subclass can't implement all the abstract methods of the parent class , Then this subclass can only be an abstract class . Again , When an interface is implemented , If interface methods cannot be fully implemented , Then this class can only be an abstract class .
6、 Abstract methods can only state , Can't achieve , Interface is the result of design , Abstract classes are the result of refactoring
7、 There can be no abstract methods in an abstract class , If you want to extend new methods of abstract classes , Subclasses will easily get these new methods .
8、 If there are abstract methods in a class , So this class can only be an abstract class
9、 Abstract methods are to be implemented , So it can't be static , It can't be private .
10、 Interfaces can inherit interfaces , And can inherit more interfaces , But classes can only inherit from one root .

5.6.3 Understand the opening and closing principles of software design OCP

Open function extension , Close source code modification, etc .

The English full name of the open close principle is Open Close Principle, The abbreviation is OCP, It is Java The most basic design principle in the world , It teaches us how to build a stable 、 Flexible systems .

The principle of opening and closing is defined as : Objects in software ( class 、 modular 、 Functions, etc ) It should be open to extension , But it is closed for modification .

Opening and closing principle , It's a design pattern , With the idea of object-oriented programming , emerge as the times require .
open , It means that it can be extended on the basis of source code , Like inheritance , Interface , Abstract classes, etc . stay JAVA in , The reason for using inheritance , On the premise that the class library can be called directly , Expand its functions . The application does not need to understand the internal logic of the encapsulated class to develop .

close : It means that it is not allowed to modify the original code . So as not to affect other existing functions , Cause functional paralysis .

5.6.4 Piling and DeBug

When the running result of the program is different from what you said you expected , How to debug code ?

(1) Pile driving : System.out.println( data );

(2)Debug Debugging tools :— Add Breakpoint Mouse click
(2.1) Master the four keys :
(2.1.1)F5: Step by step debugging ( Will enter the method )
(2.1.2)F6: Step by step debugging ( Will not enter the method )
(2.1.3)F7: End the debugging of the method
(2.1.4)F8: Go straight to the next breakpoint ( If there is no breakpoint, end the debugging )
(2.2) Can see two things
(2.2.1) Will look at variables
(2.2.2) Monitoring will be added ( Look at the expression – Check the expression , Right click Watch)

public class DebugDemo {

public static void main(String[] args) {

int a = 15;
int b = 30;
test(a,b);
System.out.println("over");
}
public static void test(int a1,int b1){

int sum = a1+b1;
if(sum>5){

System.out.println(sum);
}
}
}

5.6.5 Math Class provides three positive related methods :ceil,floor,round

How to write it

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

(1)ceil Ceiling is the English meaning of , This method means rounding up
(2)floor Floor is the English meaning of , This method represents rounding down
(3)round Method : It said “ rounding ”( namely : +0.5 Rounding down )

6 abnormal

6.1 Exception Overview

Java The abnormal (Exception) Also known as the exception , Is an event that occurs during the execution of a program , It interrupts the normal instruction flow of the program being executed .

6.2 Abnormal inheritance structure

stay Java in , All anomalies have a common ancestor Throwable( Throwable ).Throwable Specify the exception propagation mechanism available in the code through Java The commonality of any problems with application transport .
 Insert picture description here
Throwable: There are two important subclasses :Exception( abnormal ) and Error( error ), Both Java Important subclasses of exception handling , Each contains a large number of subclasses . The difference between an exception and a mistake is : Exceptions can be handled by the program itself , The mistake is that you can't handle .

Error( error ): It's a bug that the program can't handle , Indicates a more serious problem in running an application . Most of the errors have nothing to do with what the coder does , It means code runtime JVM(Java virtual machine ) What happened . for example ,Java Virtual machine running error (Virtual MachineError), When JVM When there are no more memory resources needed to continue the operation , Will appear OutOfMemoryError. When these exceptions occur ,Java virtual machine (JVM) Generally, thread termination will be selected . These errors indicate that the failure occurred in the virtual machine itself 、 Or when the virtual machine attempts to execute the application , Such as Java Virtual machine running error (Virtual MachineError)、 Class definition error (NoClassDefFoundError) etc. . These mistakes are not to be found , Because of their control and processing power in the application Outside , And most of them are not allowed when the program is running . For well-designed applications , Even if an error does occur , In essence, we should not try to deal with the abnormal situation caused by it . stay Java in , Erroneous passage Error Subclass description of .

Exception( abnormal ): It's an exception that can be handled by the program itself .Exception Class has an important subclass RuntimeException.RuntimeException Class and its subclass represent “JVM Common operations ” Error caused . for example , If you try to use a null object reference 、 Divisor is zero or array is out of bounds , Run time exceptions are raised respectively (NullPointerException、ArithmeticException) and ArrayIndexOutOfBoundException.

Exception( abnormal ) There are two main categories Runtime and non runtime exceptions ( Compile exception ). These exceptions should be handled as much as possible in the program .

1. Runtime exception All are RuntimeException Class and its subclass exception , Such as NullPointerException( Null pointer exception )、IndexOutOfBoundsException( Subscript out of range exception ) etc. , These exceptions are not checked , The program can choose to capture the processing , Or not . These exceptions are usually caused by program logic errors , Programs should try to avoid such exceptions from a logical point of view . Runtime exceptions are characterized by Java The compiler will not check it , in other words , When this kind of exception may appear in the program , Even if it doesn't work try-catch Statement capture it , It doesn't work throws The clause declares to throw it , Will also compile through .

2. Non runtime exception ( Compile exception ) yes RuntimeException An exception , They all belong to Exception Classes and subclasses . From the perspective of program syntax Is an exception that must be handled , If you don't deal with , The program can't be compiled . Such as IOException、SQLException And user-defined Exception abnormal , In general, no custom check exception .

6.3 Throwable Class

1. Returns the details when the exception occurred
public string getMessage(); //String type , The display needs to be output system....
2. Returns a brief description of when the exception occurred
public string toString();
3. Returns the localized information of the exception object . Use Throwable This method is overridden by a subclass of , Can claim localized information .
If the subclass does not override the method , Then the information returned by this method is the same as getMessage() The results returned are the same .
public string getLocalizedMessage();
4. Print... On the console Throwable Object encapsulated exception information ( Commonly used )
public void printStackTrace();//void type , You can print exception information without output 

6.4 Java Common abnormal

java Common runtime exceptions :

ClassCastException Class conversion exception
ArithmeticException Arithmetic abnormality
ArrayIndexOutOfBoundsException Array subscript out of bounds exception
NullPointerException Null pointer exception
NumberFormatException The number format is abnormal

java Common non runtime exceptions :

IOException io Abnormal flow
SQLException sql abnormal
ClassNotFoundException Class cannot find exception
FileNotFoundException File cannot find exception

6.5 Overview of exception handling

exception handling Grab and throw the model

Process one :“ throw ”: During the normal execution of the program , Once something unusual happens , An exception object is generated at the exception code , And throw the object . Once an exception object is thrown , The subsequent code will no longer execute .
On the generation of abnormal objects :① Exception objects generated automatically by the system ② Manually generate an exception object , And throw (throw)

Process two :“ Catch ”: It can be understood as an exception handling method :1. try-catch-finally 2. throws

If an exception occurs in the program and is not handled : Will eventually run to main In the method ,main Method by jvm management ,jvm The exception handling program stops running directly .

The significance of exception handling : The program can still execute correctly after an exception occurs , Does not affect the operation of the program .

6.6 Exception handling method 1 (try-catch-finally)

explain :try-catch-finally, Also called capture mode .

grammar :

//try Only once catch Can appear 1 To N Time finally appear 0 To 1 Time 
try{

// Code with possible exception 
}catch( Exception types Exception names ){

// Treatment scheme 
}finally{

// Code that must execute 
}

6.6.1 test 1:try-catch structure

package com.shuai;
/** * 1.finally It's optional . * 2. Use try Wrap up the possible exception code , In the process of execution , Once an exception occurs, an exception object corresponding to the class will be generated , according to * The type of this object is to catch Match in . * 3. once try The exception object in matches a catch when , To get into catch Exception handling in , Once the process is complete , Just jump out of the current * try-catch structure ( Without writing finally The situation of ), Continue with the following code . * 4.catch If the exception type in has no parent-child relationship , Who declared on ,, It doesn't matter who declares that . * catch If the exception type in has parent-child relationship , The subclass should be in the upper class and the parent class should be in the lower class , Order from small to large , Otherwise, the guarantee is wrong . * 5. Common exception handling methods :1)String e.getMessage() 2)void e.printStackTrace() This is more commonly used * 6. stay try Variables defined in the structure , except try The structure can't be used in the future . Want to use to declare variables outside , The assignment is in the structure . * 7. Why not write it int num; Instead of assigning more values 0, First of all, because variables want to output, they must be declared and have initialized values , And local variables * No default , once try Program error in , Direct output num,num If there is no value, the program will report an error , To avoid that , add 0 It won't affect Cheng * The sequence will not be caused by abnormal conditions num It's worth nothing to make a mistake . *8.try-catch-finally You can also nest * experience 1: Use try-catch-finally Structure handling compilation exception , So that no error will be reported during compilation , However, errors may be reported during operation , amount to try-catch-finally * Delay exceptions that may occur at compile time until they occur at run time . * experience 2: In development , Because runtime exceptions are common , So we don't usually write for runtime exceptions try-catch-finally 了 . * For compile time exceptions , We said we must consider exception handling .( If you interact with the previous page , Still have to deal with .) */
public class Demo05 {

public static void main(String[] args) {

String str="123";
str="abc";
/* Why not write it int num; Instead of assigning more values 0, First of all, because variables want to output, they must be declared and have initialized values , Local variables have no default values , once try Program error in , Direct output num,num If there is no value, the program will report an error , To avoid this kind of situation , add 0 It will not affect the program, nor will it lead to num It's worth nothing to make a mistake .*/
int num = 0;
try {

num=Integer.parseInt(str);
//int num=Integer.parseInt(str);// Something unusual happened 
System.out.println("hell0-------01");// No output 
} catch (NullPointerException e) {
 // Habitually, it is called e
System.out.println(" Null pointer conversion exception occurred ");
}catch (NumberFormatException e) {
 // A type e Only in one catch Effective in , So different catch Chinese names can be the same .
//System.out.println(" A numeric conversion exception occurred "); It's not usually written like this , Use exception class method instead of , as follows :
//String e.getMessage(): The return value of this method is String type , If you want to see it, you have to output it . Because there is a return value, you need to define variables to receive , View is about to output , It's abbreviated here .
// System.out.println(e.getMessage()); // Print exception information 
//void e.printStackTrace(): The return value of this method is void type , You don't need to output to view .
e.printStackTrace(); // Print exception details 
}catch (Exception e){

System.out.println(" Something is wrong ");// No output 
}
//System.out.println(num); Error protection cannot call , Because of the variable num stay catch As defined in , The scope is catch in .
System.out.println(num);
System.out.println("hell0-------02");// Will be output 
}
}

6.6.1 test 2:finally Use 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 in finally Use : * * * 1.finally It's optional * * 2.finally What is declared in is code that must be executed . Even if catch There's something wrong with it ,try There is return sentence ,catch There is * return Statement, etc . * * 3. Like database connection 、 I / O stream 、 Network programming Socket And so on ,JVM It can't be recycled automatically , We need to do resource management manually * Release . At this time, resources are released , It needs to be stated in finally in . * * * */
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)
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(" I will be executed ");
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(" I'm so handsome !!!~~");
finally{

System.out.println(" I'm so handsome ~~");
}
}
}

6.7 Exception handling mode 2 —(throws)

follow : The exception thrown by the subclass is less than or equal to that of the parent class .

package com.atguigu.java1;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/* * The second way of exception handling :throws + Exception types * * 1. "throws + Exception types " Write in the declaration of the method . Indicates when this method is executed , Types of exceptions that may be thrown . * Once the method body executes , Something unusual happened , An object of the exception class is still generated at the exception code , This object satisfies throws Post anomaly * Type , Will be thrown . Exception code, subsequent code , I'm not going to execute it anymore ! * * 2. experience :try-catch-finally: The real exception is handled . * throws The only way to do this is to throw the exception to the caller of the method . It didn't really handle the exception . * * 3. How to choose to use try-catch-finally Or use throws? * 3.1 If the overridden method in the parent class does not throws Handle exceptions in different ways , Then subclass overridden methods cannot be used throws, It means if * Exception in subclass override method , You have to use try-catch-finally Method handling . * 3.2 Method of execution a in , Several other methods have been called , These methods are implemented by progressive relations . We suggest that these methods use throws * The way to deal with . And the method of execution a Consider using try-catch-finally Method . * */
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) {

e.printStackTrace();
}
}
//method1 Throw out 2 Exceptions , here method2 Why does the call throw only one exception ??
// If you handle exceptions in the same way , For example, all of them are e.printStackTrace();, Then just throw an exception .
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!");
}
}

6.8 Throw an exception manually throw

Manually throw an exception. If it is a runtime exception, you can not handle it , If you throw an exception at compile time, be sure to handle it .

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();
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(" The data you entered is illegal !");
// Throw exception object manually 
// throw new RuntimeException(" The data you entered is illegal !");
// throw new Exception(" The data you entered is illegal !");
throw new MyException(" You can't enter a negative number ");
// FALSE 
// throw new String(" You can't enter a negative number ");
}
}
@Override
public String toString() {

return "Student [id=" + id + "]";
}
}

6.9 Custom exception

1. In general, and throw Continuous use , The purpose is that the exception types provided by the system are limited , If the exception generated by the program is not in the provider , You can throw your own defined Exceptions to make the exception type more precise .
2. Generally, this custom exception class , When defining this class, you should know the meaning according to the name .

package com.atguigu.java2;
/* * How to customize exception class ? * 1. Inherits from the existing exception structure :RuntimeException 、Exception * 2. Provide global constants :serialVersionUID * 3. Provide overloaded constructors * */
public class MyException extends Exception{

static final long serialVersionUID = -7034897193246939L;
public MyException(){

}
public MyException(String msg){

super(msg);
}
}

4.1.4 test 1

Receive the two numbers input by the keyboard and do the division operation

package cn.tedu.exception;
import java.util.InputMismatchException;
import java.util.Scanner;
// exception handling 
public class Test7_Exception {

public static void main(String[] args) {

// method();// Abnormal exposure -- Exceptions should not be visible to the user , In case of any abnormality, we should deal with it in time , Even preprocessing .
// method2();// Handling exceptions -- Capture 
try {

method3();// Handling exceptions -- Throw out 
} catch (Exception e) {

e.printStackTrace();// Output complete error message ( But it can only be output on the console )
}
}
// Throw exception : Add... To the method throws Exception types 1, Exception types 2…… To throw an exception 
// Be careful : The position is written after the brackets , Multiple use ”,” separate .
// public static void method3() throws InputMismatchException,ArithmeticException,Exception{

//1,Exception It is also a polymorphic application , Don't care about the type of specific exception , Anyway, it's all Exception Subclasses of , Can throw .
public static void method3() throws Exception{

// 1, Receive two integers entered by the keyboard 
int a = new Scanner(System.in).nextInt();
int b = new Scanner(System.in).nextInt();
// 2, Do division 
System.out.println(a / b);
}
// Abnormal capture :
/* * try{ There may be abnormal code }catch( Exception types Exception names ){ A reasonable solution } */
public static void method2() {

try {

// 1, Receive two integers entered by the keyboard 
int a = new Scanner(System.in).nextInt();
int b = new Scanner(System.in).nextInt();
// 2, Do division 
System.out.println(a / b);
} catch (ArithmeticException e) {

// It happened. ArithmeticException When abnormal , Will be catch Live and give a solution 
System.out.println(" The second input cannot be 0 !!");
} catch (InputMismatchException ime) {

// It happened. InputMismatchException When abnormal , Will be catch Live and give a solution 
System.out.println(" Please enter an integer twice !!");
} catch (Exception e) {

// 1,Exception It's a manifestation of polymorphism , Don't care what specific subclasses are called , Anyway, it's all Exception Subclass , Can be captured 
// If in the process , There are exceptions other than the above two exceptions , The program still needs to deal with 
System.out.println(" Please input the correct data !!");
}
}
public static void method() {

// 1, Receive two integers entered by the keyboard 
int a = new Scanner(System.in).nextInt();
int b = new Scanner(System.in).nextInt();
// 2, Do division 
System.out.println(a / b);
}
}
}

4.1.5 test 2

package cn.tedu.exception;
import java.util.InputMismatchException;
import java.util.Scanner;
// exception handling 
public class Test7_Exception {

public static void main(String[] args) {

//int data =calc(5,0);
//e.getMessage() Get exception information , The information in the object ( Illegal parameters )
// System.out.println(e.getMessage());
Try{

int data =calc(5,0);
}catch(){

System.out.println(e.getMessage());
}
}
public static int calc(int i;int j) throws Exception{

try{

return i/j;
}catch(Exception e){

e.printStackTrace();
//return 0; If the method has a return value , You can use throw Instead of return
// Will be abnormal (Runtime abnormal ) Throw to the caller , What happened was Runtime abnormal , Then the upper layer processing can also not handle , There is no need to add throws
// Will be abnormal (Checked abnormal ) Throw to the caller , What happened was Checked abnormal , Then the upper level must deal with , The method should pass throws Statement , But be aware that if you throw it to the top, it is main The best way is to try-catch, If in main If the method continues to be thrown, it will be handed over to jvm virtual machine , The virtual machine handles exceptions by killing the process , End the program . The method must add throws.
Throw new ArithmeticException(“ Illegal parameters ”);
}
}
}

4.1.6 Custom exception

When jdk Self contained exception type , When you can't meet your actual needs , You need to extend the exception system . In general , See the class name of the exception , It's just the probable cause of the problem ( And immediately see the name and know the meaning )
Usually some business problems , For example, the balance is insufficient , Password error and other problems .
Expand RuntimeException abnormal , Just inherit RuntimeException Exception or its subclass
Expand Checked abnormal , Just inherit Exception Abnormal or Exception Subclasses of , But you need to get rid of RuntimeException outside .
step :1. Just define a class 2. Inherit the corresponding exception ( Runtime exception , Or non inspection abnormalities )3. Rewrite the construction method inside .

7. Inner class

Inner class is to define a class inside a class , such as A class B class , that B Class relative A Class is an inner class , and A Class is relative to B Class is an external class .

7.1 Member inner class

https://www.bilibili.com/video/BV12J41137hu?p=76

7.2 Local inner classes

7.3 Static inner class

7.4 Anonymous inner class

copyright:author[Cool breeze AAA],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130738002886.html