final keyword
effect
Used to decorate classes, variables, constants, and methods
be careful
1.final decoration
Class is the final class, then
Cannot give subclasses
inherit
2.final decoration
Method, then this method
Cannot be
rewrite
3.final decoration
For variables, assign a value first, and then assign the value of the variable
Cannot be
modify
4. Type is
Basic data type, the value of this variable after assignment
Cannot be
modify
5. The type is
Reference type, then
No
Assign a new object, but
You can modify the
numerical value
6.final decoration
Local variables can be uninitialized first, but the value of the variable after assignment
Cannot be modified
7. Use final decoration
Member variables (including static / non static) are required
Initialize first (otherwise there will be compilation errors), and the variable value cannot be modified
polymorphic
definition
In Java, polymorphism refers to the polymorphism of behavior
How to generate
Polymorphism is a condition that occurs because the compile time type is inconsistent with the run time type
Compile time type is the type of reference variable
The runtime type is the object type from new
// --When compiling, the syntax verification of compilation is determined according to the type of compilation // --When a method is called at runtime, it is essentially a method of runtime type //Compile time type runtime type Person p = new Doctor(); // When the method is called with a reference variable, the behavior characteristics of the subclass are displayed p.eat(); //Because the compile time type of p is Person, the work method cannot be found in the Person class during compilation, and compilation error occurs p.work();//The method work() is undefined for the type Person
Premise of polymorphism
1. Reference of parent class
Objects pointing to subclasses
2. Subcategory requirements
Override parent method
Result: when the method is called by referencing a variable, a
The polymorphism of behavior shows the behavior characteristics of subclasses.
be careful:
The variable is
Non polymorphic
practice
Exercise 1
-- pet shops, there are ways to foster pets
-- Pet, there is a feeding method
-- Cats
-- Dogs
public class PetShop { // Ways to foster pets [pets] public void adoptPet(Pet pet) {//The reference of the parent class points to the subclass object pet.feed();//When the method is called, the behavior characteristics of the subclass are displayed } }
//Pet's parent public class Pet { // There are ways to feed public void feed() { System.out.println("Feed pets."); } } //Different pet classes class Cat extends Pet { public void feed() { System.out.println("Feed dried fish."); } } class Dog extends Pet { public void feed() { System.out.println("Feed the bones."); } } class Raby extends Pet { public void feed() { System.out.println("Feed carrots."); } }
//Test class public class PetMain { public static void main(String[] args) { // Pet store foster pets PetShop shop = new PetShop(); Dog dog = new Dog(); Cat cat = new Cat(); shop.adoptPet(cat);//Output feeding dried fish } }
Exercise 2
--ElectronicShop electronic repair shop has the method of repairing electronic equipment, repair(), which calls the openAndCheck method in the equipment
public class ElectronicShop { // There is a method to repair the electronic device, repair(), which calls the openAndCheck method in the device public void repair(ElectronicEquipment equipment) { equipment.openAndCheck();// Inspection and maintenance } //Write test code public static void main(String[] args) { //Electronic equipment repair shop repairs Mobile Phones ElectronicShop shop = new ElectronicShop(); shop.repair(new MobilePhone("Huawei", "Chongqing", "unicorn")); shop.repair(new Flat("Apple", "Shenzhen", "M1")); } }
--Electronic equipment
Owning attribute: name [name]\productionaddress[production point]\cpu[processor]
Owning method: openAndCheck(); Method [output name is starting, output device information]
Electronic device subclass: - mobile phone rewrites openAndCheck(); Method -- Flat rewrite openAndCheck(); Method -- Computer rewrites openAndCheck(); method
public class ElectronicEquipment { // Name [name]\productionaddress[production point]\cpu[processor] public String name; public String produtionAddress; public String cpu; // : openAndCheck(); Method [output name is starting, output device information] public void openAndCheck() { System.out.println(name + "Starting, address information of device:" + produtionAddress + " cpu:" + cpu); } //Constructor, with and without participation public ElectronicEquipment(String name, String produtionAddress, String cpu) { super(); this.name = name; this.produtionAddress = produtionAddress; this.cpu = cpu; } public ElectronicEquipment() { super(); } } class MobilePhone extends ElectronicEquipment { public void openAndCheck() { System.out.println("Starting the phone, ready for detection" + name + "Address information of the device:" + produtionAddress + " cpu:" + cpu); } public MobilePhone(String name, String produtionAddress, String cpu) { super(); this.name = name; this.produtionAddress = produtionAddress; this.cpu = cpu; } public MobilePhone() { super(); } } class Flat extends ElectronicEquipment { public void openAndCheck() { System.out.println("Starting the tablet, ready for detection" + name + "Address information of the device:" + produtionAddress + " cpu:" + cpu); } public Flat(String name, String produtionAddress, String cpu) { super(); this.name = name; this.produtionAddress = produtionAddress; this.cpu = cpu; } public Flat() { super(); } } class Computer extends ElectronicEquipment { public void openAndCheck() { System.out.println("Starting the computer, ready for detection" + name + "Address information of the device:" + produtionAddress + " cpu:" + cpu); } public Computer(String name, String produtionAddress, String cpu) { super(); this.name = name; this.produtionAddress = produtionAddress; this.cpu = cpu; } public Computer() { super(); } }
Conversion of reference type
Upward transformation
Assign the subclass to the parent class, and the subtype can be assigned to the reference variable of the parent class
Downward transformation
Assign a parent class to a child class. When referring to variables for downward conversion, you should pay attention to whether the types are compatible, which can be judged by the instanceof keyword.
Error warning: com.day0120.Doctor cannot be cast to com.day0120.Student [type incompatible] ClassCastException
instanceof keyword
-- judge whether the object in the variable is an object of a class or subclass [judge the object type stored in the variable]
The type after instanceof should inherit from the compile time type of the previous variable [subclass, parent class, this class]
Person p1 = new Doctor();//person is the parent class of doctor and student. //instanceof keyword [judge the object type stored in the variable] //The type after instanceof should inherit from the compile time type of the previous variable [subclass, parent class, this class] if (p1 instanceof Student) {//Judged as false System.out.println("yes Student"); Student d = (Student) p1; d.eat(); } if (p1 instanceof Doctor) {//Judged as true System.out.println("yes Doctor"); Doctor d = (Doctor) p1; d.eat(); }//Result output: Doctor Doctor eats
Compile time type and runtime type
Person p = new Student()
The type Person defined by the reference variable is the compile time type
The object type Student from new is the runtime type
1. When calling methods, you should pay attention to the compile time type (compile time type determines whether there will be compilation errors [syntax] when you program)
2. When running a program, it is the runtime type that determines whether there is an error (whether the object type is compatible during object conversion --- that is, instanceof can be used to judge)
For example: there are dogs and cats in animals; Dogs cannot be assigned to cats
Static type
-- the call is determined according to the compile time type of the input parameter variable
Which method
(that is, whoever participates in this method depends on whose compile time type)
//Static type: determine which method is called in the same class public class StaticTest { //In the same class, how to call which method depends on the method signature [based on the compile time type of the variable in the parameter] public void test(A a) { System.out.println("test(A a)-----------------"); } public void test(B b) { System.out.println("test(B b)-----------------"); } public void test(C c) { System.out.println("test(C c)-----------------"); } //main public static void main(String[] args) { // StaticTest test = new StaticTest(); // A a = new C(); B b = new C(); //In the same class, which method to call has determined [method signature] and [parameter data compile time type] at compile time test.test(a);// A a \ the input parameter is of type A, that is, it matches test(A a) test.test(b);// B b \ the input parameter is of type B, that is, it matches test(B b) } } class A { } class B extends A { } class C extends B { }
Dynamic type
-- the call is determined by the runtime type of the reference variable of the calling method
Which class
(that is, whoever invokes this method depends on whose
Runtime
Type)
public class DynamicTest { //1. Determine which class to call [determine the runtime type of the variable calling the method] //2. Determine which method to call [determine the compile time type of the input variable] public static void main(String[] args) { A a = new A(); B b = new B(); C c = new C(); a.test(b);// a--b \a is type A, where B is method B A a_c = new C(); a_c.test(b);// c--b \a_c is type C, B is method B B b_c = new C(); b_c.test(a);// c--a \b_c is type C and a is method a // a_c = a; b = b_c; b.test(a_c);// C--a \ B is b_c, i.e. type C, a_c is method a b_c.test(b_c);//c--b \b_c is type C, b_c is method B } } class A { public void test(A a) { System.out.println("A ---------- a");} public void test(B b) { System.out.println("A ---------- b ");} public void test(C c) { System.out.println("A ---------- c");}} class B extends A { public void test(A a) { System.out.println("B ---------- a");} public void test(B b) { System.out.println("B ---------- b ");} public void test(C c) { System.out.println("B ---------- c");}} class C extends B { public void test(A a) { System.out.println("C ---------- a");} public void test(B b) { System.out.println("C ---------- b ");} public void test(C c) { System.out.println("C---------- c");}}
Singleton mode
definition
Used to limit that the current class can only generate one instance object, then this class is called a singleton class. Ensure that the class has only one object in memory.
category
Create step
1. Setting the constructor to private does not allow external classes to create objects
2. Provide a static public method to obtain unique objects
3. Judge whether laz is empty to ensure that the object is unique
Lazy style
It is inherently non-linear and safe. Only when it is used can an object be new
//Singleton: lazy [created when used] public class SingleLaz { // 3. Define a variable to store the object of the singleton static SingleLaz laz = null; // 1. Privatize the constructor private SingleLaz() { } // 2. Provide a static method to get the singleton object public static SingleLaz getInstance() { //If the object is null, create a unique object if(laz == null) { laz = new SingleLaz(); } return laz; } }
Hungry Han style
Hungry man style is inherently thread safe. At the beginning, an object will occupy memory.
//Singleton: hungry Han style [created at the beginning] public class SingleHug { // 3. Define a variable to store the object of the singleton final static SingleHug laz = new SingleHug(); // 1. Privatize the constructor private SingleHug() { } // 2. Provide a static method to get the singleton object public static SingleHug getInstance() { //Return unique object return laz; } }
Usage scenarios
[multi threading, frequent operation, high resource consumption]
1. In the case of multithreading, generate a unique serial number [ensure that
Only unique generator]
2. IO stream operation and frequent creation of new objects will cause performance loss,
Fix unique io objects
3. Database links
Get unique database link object
Initialization and initialization block
Function of initialization block
Used to set some parameters when loading classes or creating objects
Fixed initialization operations (initializing member variables and performing loading of other classes)
Static and non static initialization
difference
Static initialization block
Execute only once (when the class is loaded),
Non static initialization block
Execute every time you create an object.
order
Static initialization block -- > non static initialization block -- > constructor
Initialize the order in the inheritance chain
-- parent static initialization block -- > child static initialization block -- > parent non static initialization block -- > parent constructor -- > child non static initialization block -- > child constructor
abstract class
definition
Abstract class:
Template [inherit from subclasses] (abstract classes can define anything that ordinary classes can define)
Abstract method
Do not know the specific implementation method, yes
If there is no method body, use
abstract decoration.
Person -->eat(){System.out.println("People eat");}[General] Person -->eat();[Abstract class]//With; ending
abstract class
The role of an abstract class is to act as a
The template is inherited by subclasses.
Features and precautions
1. Abstract class
Itself is
Objects that cannot be created[
Instantiated] that is, you cannot create an object with new, but you can
Objects of subclasses are assigned to abstract classes
Reference variables.
People p = new People();//No, abstract classes cannot be instantiated! People p = new Doctor();//doctor is a subclass object of people p.eat();
2. Subclasses inherit abstract classes. If subclasses
If the abstract method is not implemented, this class
Must be an abstract class.
be careful:
Abstract classes can inherit abstract classes and do not implement abstract methods
Why use abstract classes
1. Abstract class itself is a concept
2. As a
Templates are inherited by subclasses, so subclasses must implement abstract methods
Usage scenarios
If
For methods that do not require subclass overrides, use
Ordinary class inheritance is enough; But if you want to subclass
If you must implement the method, you need to use
Abstract classes, let subclasses inherit and override the implementation of methods.
practice
Polygon abstract class, which defines the abstract method of calculating perimeter and area
Subclasses are as follows:
--Quadrilateral
--Triangle
public abstract class Polygon {//polygon public abstract double getArea();// the measure of area public abstract double getPerimeter() ; // Perimeter }
public class Rectangle extends Polygon {//quadrilateral public double length;//long public double width;//wide @Override public double getArea() { return length * width; } @Override public double getPerimeter() { return (length + width) * 2; } public Rectangle(double length, double width) {//constructor super(); this.length = length; this.width = width; } public Rectangle() { super(); } }
//triangle public class Triangle extends Polygon { double bottom; double height; double side1; double side2; double side3; @Override public double getArea() {//Subclass is not return (bottom * height) / 2.0;// (bottom * height) /2 } @Override public double getPerimeter() { return side1 + side2 + side3; } //Full parameter constructor public Triangle(double bottom, double height, double side1, double side2, double side3) { super(); this.bottom = bottom; this.height = height; this.side1 = side1; this.side2 = side2; this.side3 = side3; } public Triangle() { super(); } }
public class PolygonMain {//Test class public static void main(String[] args) { Polygon p = new Triangle(10, 5, 10, 10, 10); System.out.println(p.getArea()); System.out.println(p.getPerimeter()); } }
Interface
definition
An interface is a special abstract class. An interface class is a
standard;
Interfaces are used to define abstract methods (define specifications)
The function of interface is decoupling [separation of definition and implementation]
Usage scenarios? Generally, interfaces are used
matters needing attention
1. Variables, common methods, initialization blocks, and constructors cannot be defined;
2. Default methods and constants can be defined
//You cannot define a normal implementation method \ but you can define a default method public void demo() {//This is a common method and cannot be defined in this way System.out.println("sdfdsf"); } //Default method default void test() {//In the interface, default means default, which is different from the function of default in the modifier System.out.println("sdfdsf"); }
3. Abstract methods are decorated with public abstarct by default
// Abstract methods \ default public abstract can also be defined in the interface public abstract void devilyData();//That is, this statement and void devilyData(); Same function
4. Constants are decorated with public final static by default
5. The interface cannot be instantiated
6. The default method can be defined in the interface, but it must be decorated with the default keyword
7. Multiple interfaces can be implemented (one class can implement multiple interfaces)
Relationship between abstract classes and interfaces
difference
An abstract class is used as a template
- Abstract methods can be defined, and the implementation must be rewritten to find subclasses.
- You can define variables, common methods, constructors, constants, and initialization blocks.
Interface as a specification.
- Abstract methods can be defined
- Constants, common methods, constructors, and initialization blocks cannot be defined.
- Only constants and default methods can be defined
Usage scenarios
To inherit from subclasses
common
Abstract classes are used for properties and methods of property (something inherits), and interfaces are not used for subclasses that inherit things. Reason: java can only inherit, but interfaces can be implemented (decoupled).
practice
Analysis topic meaning: class (there are three classes in total, police station (general class -- implementation of microphone class), police (abstract class), microphone (Interface)) -- > attribute -- > method -- > test
//Microphone [interface] public interface Phone { // Abstract method of report void report(String msg); }
//Police station PoliceHost [general] public class PoliceHost implements Phone { @Override public void report(String msg) { System.out.println(msg); } // Dispatch police public void detach() { // 1. Create a new police object Police gao = new Gao(); //Set up a microphone for officer Gao gao.setPhone(this);//new Phone() [cannot instantiate interface]; -- > New PoliceHost() [only subclasses can be instantiated] -- > this [equivalent to the object of PoliceHost] // 2. Output a little information System.out.println("Send police officer Gao to appear"); // 3. Investigation gao.scout(); } }
//Police [abstract class] public abstract class Police { public Phone phone; // Microphone public abstract void scout();// Abstract methods of investigation public Phone getPhone() {//get, set method return phone; } public void setPhone(Phone phone) { this.phone = phone; } } // Officer Li class Li extends Police { @Override public void scout() { System.out.println("Officer Li stepped on Halley and rushed to the scene for investigation"); phone.report("Officer Li's feedback: the scene was terrible! Important clues are lost!");// Feedback after investigation } } // Officer Gao class Gao extends Police { @Override public void scout() { System.out.println("Police officer Gao took a jet and rushed to the scene for investigation"); phone.report("Officer Gao's feedback: there are clues left at the scene! Continue the investigation!");// Feedback after investigation } }
public class PoliceTest { public static void main(String[] args) { PoliceHost host = new PoliceHost(); // The police station dispatched police, and officer Gao went to the scene to investigate host.detach(); } }
Callback method
Explanation: enter A [police station] into B [police officer], and then B calls A's method. This process is called callback method
For example, assign the police station object (implements in the phone interface, that is, the telephone) to the police officer, and the police officer calls back the report method in the police station (telephone).
The operation of the police officer calling the report method is called
Method.
Template method type
definition
Used as a template for subclass inheritance and extension implementation (abstract class, interface implementation)
Attribute function template
example

//This is the production model of Hummer public abstract class HummerModel { // Template method public abstract void start(); public abstract void stop(); public abstract void alarm(); public abstract void engineBoom(); public abstract void run(); }
//A model is produced according to the template public class HummerM1 extends HummerModel { @Override public void start() { System.out.println("HummerM1 start..");} @Override public void stop() { System.out.println("HummerM1 stop..");} @Override public void alarm() { System.out.println("HummerM1 alarm..");} @Override public void engineBoom() { System.out.println("HummerM1 engineBoom..");} @Override public void run() { System.out.println("HummerM1 run..");} }
public class HummerMain {//Test class public static void main(String[] args) { HummerModel m1 = new HummerM1();//The reference of the parent class points to the subclass object m1.start();//Call the implementation operation of subclasses to reflect different behavior characteristics } }
Factory mode
Used to define a factory class to produce something. (factory method should be static)
When a type is also used in multiple classes, the factory class is used to produce this type. In the later stage, the business is modified and updated, and only the factory type is changed. (realize decoupling)
- In the following scenario, this type is the output class.
Scenario explanation
There is a scenario: suppose there is a Computer class in the program that needs to combine an Output device. Now there are two choices: directly let the Computer class combine a Printer, or let the Computer class combine an Output. Which method is better?
Suppose you let the Computer class combine a Printer object. If one day the system needs to be reconstructed, you need to use BetterPrinter to replace the Printer, which requires opening the source code of the Computer class for modification. It's ok if only one Computer class in the system is combined with Printer, but if 100 classes in the system are combined with Printer, even 1000, 10000... It will mean that 100, 1000, 10000 classes need to be opened for modification. How much work it is!
To avoid this problem, the factory pattern suggests that the Computer class be combined with an object of Output type, and the Computer class be completely separated from the Printer class. Whether the Computer object actually combines a Printer object or a BetterPrinter object is completely transparent to Computer. When the Printer object is switched to the BetterPrinter object, the system is completely unaffected. The following is the definition code of this Computer class.

//Computer public class Computer { // Combined with an output device // public Output output; //The commented out code is to combine a Printer with a Computer class /*public Output getOutput() { return output;} public void setOutput(Output output) { this.output = output;}*/ // How to print information public void printData(String msg) { OutputFactory.getOutput("led").show(msg); //The effect is the same as below } /* public Output output = OutputFactory.getOutput(); public void printData(String msg) { output.show(msg); }*/ } class Dell extends Computer { // Combined with an output device // public Output output; /*public void setOutput(Output output) { this.output = output;}*/ // How to print information public void printData(String msg) { OutputFactory.getOutput("Output").show(msg); } }
//Output device [electronic display] public class Output { // How to display information public void show(String msg) { System.out.println("The display shows information:" + msg); } } class LedOutput extends Output{ // How to display information public void show(String msg) { System.out.println("LED Screen display information:" + msg); } }
//Production of output equipment -- factory class public class OutputFactory { //Production method public static Output getOutput(String type) {//return is the output object, that is, the output device is returned //Produce objects by type if(type.equals("led")) { return new LedOutput(); }else { return new Output(); } } }
Inner class
definition
Classes are included in the class in order to better hide the details of the class [linked list node](
Internal classes can inherit and implement interfaces)
classification
Non static inner class
1,
Because non static inner classes are members of outer classes, you can use public, protected, private, and static to decorate classes
2. In non static inner classes
Can only be defined
Static constant, cannot define static variable
3. When creating a non static internal class, you need to use the
The object of the external class calls the constructor of the internal class
Clothes c = new Clothes();//When creating a non static internal class, the constructor of the internal class should be called through the object of the external class Button b = c.new Button();//Buttons are non static inner classes of clothes b.test();
4. Non static internal classes can access the properties and methods of external classes, including privatized ones
5,
Non static attributes of non static internal classes cannot be accessed in external classes, and static constants can be accessed
6. In external classes
Only public, abstract and final can be used
7. Inner and outer classes have
For attributes with the same name, follow
Recent policy call
Static inner class (static)
1. Static attributes can be defined in static inner classes
2. Non static properties and methods of external classes cannot be called in static internal classes
3. Through external types, reference the constructor of static internal classes to
create object
//Create objects by referencing the constructor of static internal classes through external types Collar collar = new Clothes.Collar();//Collar is a static inner class of clothes collar.demo_test();
Anonymous Inner Class
Implements an interface or abstract class, and
Without class name
Internal classes [such as: (one-time) thread applications,
Functional interface, event listening operation] [use in combination with abstract classes and interfaces]
characteristic
1. Use only once(
disposable
)
2. There is no need to define a Java file
3. Those without names are called anonymous
public interface Phone { // Abstract method of report void report(String msg); }
public class PhoneMain { public static void main(String[] args) { //Anonymous inner class: one time [in thread], functional interface, event listening operation //The operation on the right side of the expression is actually to create an object that implements the internal class of the Phone interface Phone p = new Phone() { @Override public void report(String msg) { System.out.println("Received data:"+msg); } }; p.report("nihao "); //Example: thread (one-time operation) Thread t = new Thread( new Runnable() { @Override public void run() { // System.out.println("Buy hamburgers!"); } }); t.start(); } }