1: Object oriented thought
1. Characteristics of object-oriented thought
1)Conform to the habits of thought and behavior in the real world! 2)Let's turn the executor into the commander(The role has changed!) 3)Simplify complex things!
2. Object oriented design principles in Java
You need to constantly create objects,Use object,Command the object to do things
3. Three characteristics of object-oriented
encapsulation,inherit,polymorphic
2: Relationship between classes and objects in object oriented
1. Concept of class and object
Class: it is a collection of related attributes and behaviors (it can be understood as a blueprint or template for constructing an object, which is an abstract concept) Object: it is the concrete embodiment of this kind of things (it is a concrete instance created with the class as the model and a concretization of the class) For example: class student monitor is an object
2. Definition of class
Class is a set of attributes and behaviors to describe things in the real world!(Defining a class is actually defining the members of the class(Member variables and member methods)) Member variable (instance variable): it is the attribute (attribute) of a thing:Age,height,Gender,weight,(name) Member method: the behavior of things (continuous learning).../Basic human.) 1):Defining member variables: it is the same as defining variables before, but the position has changed. In a class, outside a method. 2): Define member method: it is the same as the previous definition method, except that static Remove
3. Create object format
Class name object name = new Class name() ; Assign an attribute to a specific person : Object name.Member variable= value; (It needs to be consistent with the data type!) User functions:study,Play games,sleep Object name.Legal name of member party() ;
Examples of class students:
//Define student classes class Student{ //Attribute ----- > member variables (name, age, class, gender) String name ; //full name int age ; //Age String studentClass; String gender ; //Gender //Behavior: ------ > member method (remove static) (study, play games, sleep) public void study(){ System.out.println("Learning object orientation...") ; } public void playGame(String name){ //local variable System.out.println("Students play with him"+name) ;} public void sleep(){ System.out.println("If you are tired of learning, you need to rest...") ; } } //Test class name: the java file name is consistent with the class name of the current test class! class StudentTest{ public static void main(String[] args){ //Test your student class just now //Format for creating objects: //Class name object name = new class name (); Student student = new Student() ; //To assign an attribute to a specific person: //Object name Member variable = value; (it needs to be consistent with the data type!) student.name = "Gao Yuanyuan" ; //full name student.age = 39 ; student.studentClass = "JavaEE2008" ; student.gender ="female" ; System.out.println(student.name+"----"+student.age+"----"+student.studentClass+"---- "+student.gender) ; //Call object name //Object name Member method name (); student.study() ; student.playGame("Eat chicken") ; student.sleep() ;}}
4. Class initialization process
with:Student s = new Student();take as an example 1)load Student.class File into memory 2)Stack memory is s Open up space 3)Make room for student objects in heap memory 4)Initialize the member variables of the student object by default 5)Display and initialize the member variables of the student object 6)Assign a value to the member variable of the student object through the construction method 7)After initializing the student object, assign the object address to s variable
3: Three characteristics of object-oriented
(1) Encapsulation
1. Concept of packaging
Hide the internal implementation details of the object as much as possible,Control object modification and access rights Java Provide such a technology:Privatize the member variables of a class,The outside world cannot be accessed directly,But there are some public ways(set/get...)Indirect access
2.private keyword:
private:Private,Inaccessible to the outside world!Can only be accessed in this class(However, private member variables can be accessed indirectly through public member methods/Member method)It can modify member variables,You can also modify member methods set and get Method is the only channel for the outside world to access the private properties of the object,The method can detect and filter the data internally
3. Construction method
What is a construction method? characteristic: 1)The method name is the same as the class name 2)There is no specific return value type 3)even void none format:Permission modifier method name and class name are the same(){ } Function of construction method:Data initialization for members of an object! matters needing attention: 1)When writing a class,No parameterless constructor provided,The system provides parameterless construction method by default! 2)If the developer provides a parameter construction method,The system will not provide parameterless construction methods,Therefore, the parameter free construction method is always given!
4. Several ways of assigning values to member variables
1)Or assign values directly(Direct display initialization) (Not recommended!) 2)adopt setXXX(xx):assignment 3)Assignment by parametric construction method
(2) inherit
1. Concept of succession
Extract the common contents of some classes,Defined separately in a separate class,Let this independent class and these multiple classes produce a is a Relationship between(Inheritance relationship:extends)
2. Benefits of inheritance
1)It improves the reusability of the code 2)Improved code maintainability 3)Inheritance relationship between classes,Is a prerequisite for polymorphism!
3. Characteristics of inheritance
1)stay Java in,inherit(Between classes),Only single inheritance is supported,Multiple inheritance is not supported! 2)although Java in,inherit(Between classes)Multiple inheritance is not supported,But you can inherit at multiple levels!
4. Precautions in succession
1)The subclass inherits the parent class,Cannot inherit private members of a parent class(Member variable,Member method), reason:The outside world decorated by private cannot be accessed,However, it is accessed indirectly through public access methods 2)The subclass inherits the parent class,Cannot inherit constructor of parent class,But you can pass super keyword,Indirect access All constructors of subclasses access the parameterless constructors of the parent class by default! Why access the parameterless constructor of the parent class?Purpose of construction method:Just for data initialization 3)Due to inheritance,Subclass objects are created,When initializing subclasses(Execution construction method),The data of the parent class may be used,The parent class must be initialized first(Execute the construction method of the parent class first),The parent class initialization is complete,Subclass initialization(Hierarchical initialization!) be careful:The first sentence in the construction method of each subclass exists by default super() ; Can not write(Hidden) super:Represents the spatial identity of the parent class(Represents the address value reference of the parent object) 4)The constructor of the subclass accesses the parameterless of the parent class by default,If no parameterless constructor is provided in the parent class?What will you do Compile and report errors,Because the parent class has a parameter constructor,The system will not provide parameterless,And because all construction methods of the subclass access the parameterless of the parent class by default,So I made a mistake! How to solve it? 1)Manually give the parameterless construction method of the parent class 2)All construction methods of subclasses can be,The default access to the parent class has parameters The first sentence of the subclass's construction method:super(xxx),One of all construction methods in the subclass can be initialized by the parent class! 3)Parametric construction method through subclass,visit this()Nonparametric construction method of this class,When accessing the parameterized constructor of the parent class through the nonparametric constructor of this class
6. After adding inheritance, the access of class members
1)The name of the member variable in the subclass is consistent with that in the parent class:follow"Proximity principle" 1.1)Find the local location of the subclass first,If it exists,Just use; 1.2)If the local position is not,Then find it in the member position of the subclass,If so,Just use; 1.3)If there is no in the member position of the subclass,Then find it directly at the member position of the parent class,Use when you have; 1.4)If the member position of the parent class does not exist,Then you're wrong,This variable does not exist! 2)Member method names are consistent First find out whether this method exists in the subclass,If it exists,Just use,The method of the parent class will be overwritten(I'll talk about method rewriting later),If the subclass cannot find this method,Just find it in the parent class,Use when you have;If none is found in the parent class,It's wrong!
7. The difference between this and super
this:Represents the object address value reference of the current class super:Represents the spatial identity of the parent class(Address value reference of parent object) Differences in accessing member variables this.Member variable;Member variables of the current class accessed super.Member variable;Member variable of the parent class accessed Differences in access member methods this.Legal name of member party() ;Is the member method of the current class accessed super.Legal name of member party() ;The member method of the parent class is accessed Differences in access construction methods: this() :The parameter free construction method of this class is accessed this(xxx):Access the parameterized constructor of this class super():The parameterless constructor of the parent class is accessed super(xxx):The parameterized constructor of the parent class being accessed
(3) Polymorphism
1. The concept of polymorphism
The different states of a thing at different times(Changes in heap memory)
2. Premise of polymorphism
1)Inheritance relationship must exist 2)There must be a way to rewrite 3)Need to exist:A parent class reference points to a child class object (Upward transformation:Use the parent class of things,You must look to the left!) format:Parent class name object name = new Subclass name() ;
3. Polymorphic member access characteristics
1)Member variable: Compile look left,Run and look to the left 2)Member method:(Non static):Look at the left,Run right(Because there are methods for subclasses to override the parent class:Method rewrite) 3)Static member method:Compile look left,Run left(The subclass has the same static method as the parent class,Static methods are class dependent,No overrides exist!,Access mode:Class name.Method name()) 4)Construction method:Due to inheritance,Hierarchical initialization is also required!
4. Benefits of polymorphism
1)It improves the scalability of the code(By polymorphism) 2)It improves the reusability of the code,Maintainability(Guaranteed by inheritance)
5. Disadvantages of polymorphism
Cannot access subclass specific functions! How to solve it? Mode 1:You can create subclass concrete class objects :Subclass name object name = new Subclass name() ; Object name.Access the subclass's own functions; however,Not good,From the perspective of memory,Generate a memory space in heap memory(Compare memory consumption!) Mode 2:The third condition of polymorphism:A parent class reference points to a child class object (Upward transformation) Fu f = new Zi() ; brain storm:Casts a reference from a parent class to a reference from a child class(Downward transformation) Zi z = (Zi)f; * benefit:No need to re new object,Heap memory is more memory efficient! prerequisite:To use downward transformation,Upward transformation must be used first! matters needing attention: Improper use of polymorphic downward transformation,The program has an exception: Generate a ClassCastException:Run time exception(RuntimeException)One is caused by type mismatch when using downward transformation!
IV Three keywords
(1) abstract keyword
1.abstract: modify class, modify method: abstract meaning!
1)Modify class time:This class is an abstract class,Abstract classes cannot be instantiated directly 2)When modifying methods:This method is an abstract method,There is no method permission modifier for the method body(public) abstract Return value type method name() ;
2. Abstract class
1.concept:In a class,Give a declaration of a function(Abstract method:Method without method body),Then this class is defined as an abstract class! 2.essence:Enforce what subclasses must do 3.Characteristics of abstract classes: 1)Member variable: You can define constants,You can also define variables 2)Member method: You can define abstract methods(Must have abstract),You can also define non abstract methods 3)Construction method: Or inheritance,Construction method:Initialize data---->Hierarchical initialization! 4.Considerations in abstract classes 1)If in a class,There are abstract methods,Then this class must be an abstract class;Abstract classes are not necessarily abstract methods,There can also be non abstract methods 2)How to instantiate abstract classes? How do abstract classes create objects Abstract classes cannot be instantiated directly! ,Instantiate through specific subclasses format:Parent class name object name =new Subclass name() ; Abstract class polymorphism 3)Subclasses of abstract classes: Subclass or concrete class,Or abstract classes Subclasses are concrete classes,It can be instantiated directly in the form of abstract class polymorphism! Subclasses are abstract classes,You should also provide the most specific subclasses,Otherwise, it cannot be instantiated(meaningless!) 4)When defining abstract methods in abstract classes,Then the abstract method must be decorated:abstract,Cannot be omitted!
(2) static keyword
1. Overview of static keyword
1.static Keywords can be used to modify member variables or methods,Static attributes are shared spaces held by the entire class,Any object modification,Will affect other objects
2. Features of static keyword:
1)cover static Decorated member,Loads as the class loads (Class is loaded once!)When loading classes,The object has not yet been created 2)Prior to the existence of objects, the creation of objects is after the class loading 3)Have been shared,Shared meaning(this sentence:Tell us when to use it static Modifier variable,Methods can be described to be shared,When sharing) 4)The most important feature: cover static Modified variables and methods can be accessed directly by the class name!(Recommended class name direct access) These are static Modifier variable/method,It can also be accessed by object name(Not recommended!)
3. Precautions for static keyword:
1)static Not in keyword this and super Keyword 2)Questions about access: Non static member method,You can access static variables,You can also access non static variables, static methods and non static member methods Static methods can only use static variables/method
4. Differences between static variables and member variables
1) Belong to different Static variable:It belongs to class, so it is also called class variable Member variable:It belongs to object, so it is also called instance variable(Object variable) 2) Different locations in memory Static variable:Static area stored in method area Member variable:Stored in heap memory 3) Different life cycles Static variable:Load as the class loads and disappear as the class disappears Member variable:Exists with the creation of the object and disappears with the disappearance of the object 4) Call different Static variable:It can be called by class name or object Member variable:Can only be called by object name
(3) final keyword
1. Characteristics of final keyword
1).final Final representation,Final state,Cannot change! 2).final Modifier class,This class cannot be inherited! 3).final Member variables can be modified,The variable is now a constant(memory-resident!) 4).final Modified variable:Can only be assigned once(Its value can no longer be changed!),When customizing constants:public static final Data type variable name = initialization; 5).final Member methods can be modified,This method cannot be overridden.
2. What is the difference between variables and reference types of basic types modified by final?
1. final Modify the basic data type of the variable:Its data value can no longer be changed(Specific data values) 2. final Modified reference data type,Its address value can no longer be changed(However, the value of the member variable does not affect!)
V Interface
1. Concept
Is the extended function of describing a thing,Something that is not in itself,If the thing wants to use this extension,The function of the interface must be realized
2. Definition format of interface
interface Interface name(follow"Nomenclature of large hump"){ ... } Methods in an interface can only be abstract methods,Cannot have method body
3. Characteristics of interface members
1)Member variable: Can only be constant,There are default modifiers that are statically decorated:public satic final...(It can be omitted!) 2)Member method:Methods in an interface can only be abstract methods,There are default modifiers:public abstract(It can be omitted!) 3)Construction method:Interface has no constructor! The implementation class and interface of interface are:implements Implementation relationship,The implementation class of the interface--->be called"Sub implementation class of interface" Interfaces cannot be instantiated directly ,Implemented through subclasses format: Interface name object name =new Sub implementation class name() ; //Interface polymorphism
4. On Relations
1).Between classes:Inheritance relationship,Only single inheritance is supported,Multiple inheritance is not supported,But you can inherit at multiple levels! 2).Between class and interface:Implementation relationship,A class inherits another class at the same time,Multiple interfaces can be implemented! 3).Inheritance relationship between interfaces,Can inherit alone,You can also inherit more
5. Differences between abstract classes and interfaces
1)Differences in membership abstract class:Member variable:You can define constants,Variables can also be used Member method:It can be an abstract method,It can also be a non abstract method Construction method:existence,There is no parameter structure/Parametric structure,Initialize data! Interface:Member variable:This is a constant:There are default modifiers public static final... Member method:Can only be abstract methods Construction method:No construction method exists 2)Relationship differences: Between classes: extends,Single inheritance,Multiple inheritance is not supported,But you can inherit at multiple levels! Classes and interfaces:Implementation relationship:implements: While one class inherits another class,Multiple interfaces can be implemented! Interface and interface:Inheritance relationship:extends,Can inherit alone,You can also inherit more! 3)Differences in design concepts abstract class:Inheritance ensures the reusability of code,Polymorphism ensures the extensibility of code----Embody a"is a"Relationship between Interface:Is an additional feature,It embodies a kind of"like a"Relationship between
Vi Formal parameter and return value problem
1. Formal parameter problem of method: (reference type)
1).If it is a specific class,The object of this concrete class needs to be passed! 2).If it is an abstract class type,The actual parameter requires a subclass object of the abstract class! 3).If it is an interface,The actual parameters need to implement the subclass object of this interface!
2. Return value of (reference type)
1).If it is a concrete class type:Need to return return This concrete class object! 2).If an abstract class:The method needs to return the subclass object of the abstract class or the anonymous inner class of the abstract class! 3).Interface type:You need to return the sub implementation class object of the interface or the anonymous inner class of the interface!
VII Four permission modifiers
private Private Default modifier (No modifiers are added) protected(Protected) public(Public,Maximum access) public protected default private In this class under the same package Y Y Y Y In subclasses under the same package/Irrelevant class Y Y Y Different steamed stuffed bun classes Y Y Unrelated classes under different packages Y
VIII Code block
java Medium code block:use{}Wrapped content,It's called a code block!
Classification of code blocks
1)Local code block:Defined in local location{},effect:Define the life cycle of the variable 2)Construct code block:Defined in the member location of the class{}, characteristic:In the current class,Execute construction code block first,Then the construction method is executed.(The construction code block is executed before each execution of the construction method) Function of constructing code block:Initialize the data of the current class!(Rarely used,Written examination questions!) 3)Static code block:stay{}Add before static static{ ....} Static code blocks are loaded as classes are loaded,Because the class is loaded once,The static code block is executed once! priority:Static code block > Construct code block >Construction method
IX package
1. Concept of package
Folder used to store bytecode files(catalogue)
2. Package naming rules
All lowercase,Intermediate use.Separate or underline (Reverse writing of company domain name,middle.perhaps_separate)com.hsbc.www.xxxx
3. Package compilation
1.Compiling and running under the same package: Manual mode 1)First in HelloWorld.java In the directory where the file is located,use javac For this java Compile the source file,Will produce HelloWorld.class file 2)Manually create the directory of the corresponding package com qianfeng 3)Will 1)---->After compilation HelloWorld.class File in 2)In subfolders in 4)function:Run with package java com.qianfeng.Class name Automatic mode: 1)Compile against source files javac –d . java Source file name.java --- >take class The file is stored under the specified package 2)Just run it directly:java Package name.Class name --->enter 2.Compiling and running under different packages: 1)The currently imported class:Compile:Enter the current directory:javac -d . Demo.java 2)Enter the current directory:javac -d . Test.java 3)java com.qianfeng.Test; function java Package name.Class name
X Inner class
1.concept:Define another class in one class Eg:stay A Class B class,Just B Class is called A Inner class of class;take A Class is called B Outer class 2.characteristic:Members of the inner class can directly access members of the outer class, including private members! When a member of an external class accesses a member of an internal class,Not directly accessible,//Instead, it is accessed through internal class objects
(1) Member inner class
1.How do you want to access internal members of a class: Fixed format: External class name.Internal class name object name = External class object.Inner class object; Modifier in inner class of member: private:Guaranteed data security static modification:Treat static inner classes as static members of outer classes! 2.static Modification characteristics: 1).Member methods of static inner classes(Static or non static),Only static members of external classes can be accessed! 2).Non static member inner class. Members can only be non static. 3).The methods after the inner class is statically modified can be divided into static and non static. Their access is different from not static. Accessing non static methods: external class names.Internal class name object name = new External class name.Internal class name(); Access static method: access the object created above, or external class name.Internal class name.Method name();
(2) Local inner class
1.Classes defined in local locations 2. Members of a local inner class can directly access members of an outer class,Including private 3. How do external class member methods access members of local internal classes? *In the member method of the current external class,Just create an internal class object and call its methods 4.Interview questions: When a local internal class accesses a local variable,Why? JDK7(JDK7 before,contain JDK7 edition)Using local variables final modification?*JDK8 The version has been optimized for local variables(Already defined final modification) Life cycle of local variables:Exists with method calls,Disappears as the method is called,Because the member methods in the current local inner class are still using local variables,Indirectly through the creation of internal class objects in the member methods of external classes,Ask the member methods of the inner class---Accessing local variables,Objects are not immediately recycled,Need to wait GC Recycle in idle time,The member methods of the inner class are still being accessed,You need to define the current local variable as a constant---Fixed value in memory!
(3) Anonymous inner class
1.Local inner class without name,It is a simplified format for inner classes 2.format:new Class name(Abstract class name)/Interface name(){ override method .... }; give an example: new Person(){ //Person: abstract class //override method public void love() { ... } } ; 3.. The nature of anonymous inner classes:It is the object that inherits the abstract class or implements the subclass of the interface!