object-oriented
Understanding of object-oriented knowledge points
object-oriented:
It is the designer's thinking. It is when creating a product. It grasps and analyzes the whole system from a macro perspective.
Use object-oriented when solving complex problems that require collaboration. That is, how to design this thing? For example, building a car is object-oriented thinking. (overall design)
Facing the process, who will do it? Class / method as the minimum unit
Process oriented:
It is the thinking of the executor and the use of process oriented when solving simple problems. For example: how to drive? Is process oriented thinking. (execution and processing of data)
Process oriented thinking how to do? Function as the minimum unit
They complement each other and are not independent.
Properties are exclusive and methods are shared.
Overloading of methods
About classes, methods, constructors
attribute
A class can be regarded as a template or drawing. The system creates objects according to the definition of the class.
Class name: class. The Object is called instance, and the target is called instance.
Attributes are the data or static characteristics used to define this class or this class of objects.
Method is used to define the behavior characteristics and function implementation of the class or the class. Methods are abstractions of the behavioral characteristics of classes and objects. Methods are very similar to procedure oriented functions.
Method is actually a common feature of all attributes under this class.
Four key points of constructor:
1. The constructor is called through the new keyword!
2. Although the constructor has a return value, it cannot} define the type of return value (the type of return value must be this class). Return cannot be used in the constructor to return a value
3. If we do not define a constructor, the compiler will automatically define a parameterless constructor. If defined, the compiler will not add it automatically!
4. The constructor's method name must always be the same as the class name (the class name after class)
Function of constructor: it is not to create an object, because the object has been created before creation. And the object has a default initial value
The constructor is only called to assign values to attributes.
⚠️ Note: we generally do not initialize in the constructor, because the value of each attribute is the same.
After reloading the constructor, the system will not empty the constructor for you. At this time, the call will make an error
It has nothing to do with the order. You can write it at will
Differences among member variables, local variables and static variables
In the (member variable) stack, in the (local variable) heap, in the (static variable) method area.
(1) Different positions in the class
Member variable: outside method in class
Local variable: in the method definition or on the method declaration (in the code block)
(2) Different locations in memory
Member variables: in heap
Local variables: in stack
(3) Different life cycles
Member variable: exists with the creation of the object and disappears with the disappearance of the object
Local variable: exists with the method call and disappears with the method call
(4) Different initialization values
Member variables: have default values
The default value must be defined before the local value can be used. Initialization value required
Usage of this
The essence of this is the address of the created object Because it was created before the constructor method call. Therefore, this can also be used to represent the current object in the construction method.
Constructors are not used to create objects, but to initialize the properties of objects
Deepen understanding of this:
4 steps to create an object:
1. Allocate the space of the object and initialize the object member to 0 or empty
2. Perform explicit initialization of attribute value (for example, int ID; which defaults to 0, int id =3, then 3)
3. Execution construction method
4. Return the address of the object to the relevant variable
The most common usage of this:
1.this is used to indicate the current object. The most commonly used form (in the construction method, it points to the initialized object) is as follows
public User(int id, String name) { System.out.println ("Initializing already created objects" + this);//this refers to the newly created object this.id = id;//Without writing this, you cannot distinguish between the member variable id (in the heap, outside the method in the class, there is a default value) and the local variable id (in the method definition or method declaration, it must be defined in the stack before assignment can be used) this.name = name; } public void login(){ System.out.println (this.name+"Login required!");//If you don't write this, the effect is the same } public User(int id,String name,String pwd){ this(id,name);//this() can be used to call other constructors, but it must be on the first line }
2.this can be used in overloaded construction methods, but it must be in the first line
3.this cannot be used in static method (this is a dependent object, there is no object in main, and it belongs to class)
static usage
public class Demo { int id; static int sid; public void a() { System.out.println ("---------a"); System.out.println (sid); System.out.println (id); } //1.static and public are modifiers. They are juxtaposed and have no order. Anyone can write them first static public void b() { //sid is loaded before the object // a();//3. Non static methods cannot be accessed in static methods System.out.println ("---------b"); System.out.println (sid); // System.out.println (id);//2. Non static properties cannot be accessed in static methods // System.out.println (this.id);//4. This keyword cannot be used in static methods } public static void main(String[] args) { Demo d = new Demo(); // Demo.a();//5. Non static methods can use object names The method name cannot be called by class Method name d.a (); Demo.b ();//6 'static methods can use object names method; Class name Method name (recommended) to call d.b (); b();//Can be called directly in the same class } }
The member variables declared by static are static member variables / class variables. The life cycle is the same as that of the class. The declared methods are called static methods. Static modifiers are located in the class, not in the object
Virtual machine memory memory simple three subareas:
Stack stack, heap heap, method area
The construction method is carried out in the stack, and the method code is in the method area
Features of virtual machine stack:
1. Stack describes the memory model of method execution. Each method will create a stack (storing local variables, operands, method exits, etc.) when called
2. The JVM creates a stack for each thread to store the method information executed by the thread (actual parameters, local variables, etc.)
3. The stack is thread private and cannot realize thread sharing
4. Stack storage, first in first out, last in first out
5. Stack is a continuous memory space with fast system allocation speed. The construction method needs to open up a stack frame
heap features:
1. Heap is used to store created objects and arrays (arrays are also objects)
2. The JVM has only one heap, which is shared by all threads
3. Heap is a discontinuous memory space with flexible allocation and slow speed
Characteristics of method area (static area, also heap):
1. It is only used to store information related to classes and constants
2. Store the content that will never change or be unique to the program. (class information [class object, static variable, string constant)
Memory analysis
Summary:
1. When creating an object, the Person class bytecode information will be loaded in the method area first, and the default object will be created in the heap. It is initialized by default and has an address
2. After that, the new keyword will be called and the constructor will be called. The constructor is a method that will open up a stack frame. First assign the value to the formal parameter, and then assign the value to the local variable to complete the assignment. The stack of methods (shape, local variables) disappears in the stack. (the string will be in the constant pool in the method area)
3. The object has been created. Assign the value to P.
(1) Simple code analysis
(2)
(3)
Result analysis:
Package import
package
Package name: the domain name can be written upside down, plus the module name, which is convenient for internal management. For example: com sur. test
Solution: class name and class management
com.gao and com gao. Car, these two packages have no relationship, but they are completely independent
Main packages in jak
java.lang contains the core classes of the Java language. For example: String, Math, System, etc. (can be used directly)
java.awt
java.net
java.io
java.util
**
Import class import
If you use a class with other packages, you need to use import to import, which can be called directly through the class name in this class
Note: java is imported by default All classes under Lang package can be used directly;
If you import two classes with the same name, you can only use package name + class name to display the calling related classes. For example:
java.util Date d = new java.util.Date();
Static import:
Static import is used to import the static properties and static methods of the specified class, so that we can directly use the static properties and static methods.
import static java.lang.Math.*;//Import all static properties of the Math class import static java.lang.Math.PI;//Import PI attribute of Math class
inherit
Role of inheritance:
1. Code reuse makes it easier to expand classes; 2. Facilitate the modeling of things (reuse of the same content)
Extensions
Inheritance can make a subclass have a parent class attribute and method Or redefine and append attributes and methods.
**
Key points of use:
1.Java is single inheritance (a subclass can only have one parent class), without multiple inheritance
2. In Java, there is no multi inheritance of classes and interfaces.
3. the subclass inherits the parent class and obtains all the properties and methods of the parent class (except the parent class constructor)
4. If extensions is not called when defining a class, the parent class is Java lang.Object
public class Person/*extends object*/ {//Parent class String name; int height; public void rest() { System.out.println("rest"); } public static void main(String[] args) { Student w = new Student("zhangsan",180,60); System.out.println(w instanceof Person); }//The use of instanceof, } class Student extends Person {//Subclass, which inherits the properties and methods of the parent class // int id; // String name; int score; // public void rest() { // System.out.println("rest"); // } public void study() { System.out.println("study" + this.name); } Student(String name, int height, int score) { this.name = name; this.height = height; this.score = score; } }
instanceof operator
instanceof is a binary operator, with objects on the left and classes on the right. When the object is an object created by the right class or subclass, return true, otherwise false. Code above.
**
Override of method:
Subclasses override the methods of the parent class
Three key points of method Rewriting:
1. "= =" method name and formal parameter list are the same
2. "< =" return value type and declared exception type, and the subclass is less than or equal to the parent class (for example, the parent class is person, and the subclass cannot be object)
3. "> =" access permission (e.g. public), and the subclass is greater than or equal to the parent class
package Test; import org.w3c.dom.ls.LSOutput; public class TestOverride {//Overriding is a method by which a subclass overrides its parent class. public static void main(String[] args) { Vehicle v1 = new Vehicle(); Vehicle v2 = new Vehicle(); Vehicle v3 = new Vehicle(); v1.run(); v2.run(); v3.run(); v2.stop(); v3.stop(); } } class Vehicle {//Vehicles public void run() { System.out.println("Run..."); } public void stop() { System.out.println("Stop"); } } class Horse extends Vehicle{//Horses are also means of transportation public void run(){ //Override parent method System.out.println("Four hooves flying"); } } class Plane extends Vehicle{ public void run(){//Redefine parent method System.out.println("Fly in the sky"); } public void stop(){ System.out.println("You can't listen in the air"); } }
final keyword
Function of final keyword:
Modified variable: the variable modified by him cannot be changed. Once the initial value is assigned, it cannot be re assigned.
Modifier method: this method cannot be overridden by subclasses. But it can be overloaded.
Decorated class: decorated class cannot be inherited
Inheritance and composition
Is a uses inheritance, such as Student is a person; has a combination, such as the relationship between notebook and chip
The core of "composition" is to "take the parent object as the attribute of the child class". Then, the child class obtains the attribute and method of the parent class by calling this attribute.
package Test; public class Test { public static void main(String[] args) { Student s =new Student("Gao Qi",172,"Java"); s.person.rest();//s.rest() } } class Person{ String name; int height; public void rest(){ System.out.println("Take a break"); } } class Student /*extends Person*/{ Person person = new Person(); String major; public Student(String name,int height,String major){ //Naturally have the properties of the parent class this.person.name=name;// this.name = name; this.person.height=height;//this.height = height; this.person.rest(); this.major=major; } }
Object class
Object is the root base class of all Java classes. If the parent class specified by the extends keyword is not used in the class declaration, the object class is inherited by default.
All properties and methods except construction methods are inherited. But not all can be used.
Structure tries to use the shortcut key command+7 to see the source code Command + left key
Common strings:
toString method
The public String to String() method is defined in the Object class, and the return value is of String type.
public String toString(){
return
}
==And equals methods
"= =" indicates whether the two sides are the same. If it is a basic type, it means equal values; if it is a reference type, it means equal addresses, it means the same object; otherwise, it means different.
Automatically generate constructors, get, set methods, equal, etc. Shortcut key: control+return
super keyword
super can be regarded as a reference to a direct parent object
encapsulation
Encapsulation is one of the three characteristics of object-oriented. Reasonable encapsulation of the program makes external calls more convenient and more conducive to cooperation. At the same time, it is also easier for the implementer to modify and revise the code.
Function and meaning
Programming pursues "high cohesion and low coupling". High cohesion means that the internal data operation details of the class are completed by themselves, and external interference is not allowed; Low coupling is to expose only a small number of methods for external use, so as to facilitate external calls as much as possible.
advantage
- Improve code security
- Improve code reusability
- "High cohesion": encapsulate details, facilitate modification of internal code and improve maintainability
- "Low coupling": simplify external calls, facilitate the use of callers, and facilitate expansion and cooperation
Encapsulation - use access control characters
Two details about Protected
If the parent class and the child class are in the same package, the child class can access the Protected member of the parent class or the Protected member of the parent object
If the subclass and the parent class are not in the same package, the subclass can access the Protected members of the parent class, but not the Protected members of the parent class object
Use details of package
Simple rules:
- Properties generally use private access rights
- After the attribute is private, the corresponding get/set method is provided to access the relevant attribute. It is usually decorated with public to provide attribute assignment and reading operations (the boolean variable get method starts with is)
- Methods: some auxiliary methods only used for local classes can be decorated with private. It is hoped that the methods called by other classes will be public
be careful:
Set and get are used to get data. Moreover, when using set and get methods in a class, they are followed by some specific words to form method names with specific meanings, such as set xxx() and get xxx(), which means setting XXX and obtaining XXX. (shortcut key: return + control)
polymorphic
Concept: polymorphism refers to the same method call, which may have different behaviors due to different objects.
Key points of polymorphism
- Polymorphism is the polymorphism of methods, not attributes (polymorphism has nothing to do with attributes)
- There are three necessary conditions for polymorphism: inheritance, method rewriting, and parent class reference pointing to child class objects
- After the parent class reference points to the child class object, the polymorphism occurs when the parent class calls the method overridden by the child class
package com.bjsxt.polymophism; public class Animal { public void shout(){ System.out.println("Let out a cry"); } } //Independent class class Dog extends Animal{ @Override public void shout() { System.out.println("Woof, woof"); } } class Cat extends Animal{ @Override public void shout() { System.out.println("cat "); } } class Tiger extends Animal{ @Override public void shout() { System.out.println("wawaa"); } }
package com.bjsxt.polymophism; public class Test { static void animalCry(Animal a) { a.shout();//Polymorphism!!! } public static void main(String[] args) { //create object Dog d = new Dog(); animalCry(d);//animal a =d ; A parent class reference points to a child class object animalCry(new Cat());//animal a =new Cat(); A parent class reference points to a child class object animalCry(new Tiger()); } }
Object transformation
The parent class reference points to the child class object. We call it upward transformation, which belongs to automatic transformation.
The parent class after upward transformation refers to a variable, which can only call its compiled type method, not its runtime method. At this time, we need to carry out type coercion, which is called downward transformation!
//Test type conversion Animal a = new Dog();//Up type conversion, automatic Animal b = new Cat(); a.shout(); // a.seeDoor(); Need to strengthen Dog d2 =(Dog) a;//Forced type conversion, downward type conversion, parent class, rotor class d2.seeDoor();//You can only call the methods of its compilation type, not the methods of its runtime type. At this time, you need to turn strongly, which is called downward transformation! Cat c4 =(Cat) b;// c4.catchMouse(); Cat c3 =(Cat) a;//java. Classexception. Castexception, type conversion can not be performed c3.catchMouse(); } }
Abstract method - abstract class
Abstract method
Use abstract to modify a method. There is no method body, only a declaration. What is defined is a specification. It tells subclasses that they must provide concrete implementations for abstract methods
abstract class
A class that contains abstract methods is an abstract class. The specification is defined through the abstract method, and then the subclass must define the specific implementation. Through abstract classes, we can strictly limit the design of subclasses and make subclasses more common
package com.bjsxt.abstractClass; public abstract class Student { private String name;//Common properties and methods are not affected abstract public void study();//After defining the abstract method, the class becomes an abstract class abstract public void exam();//Abstract class methods must be implemented by subclasses //Create method, independent of abstract class public String getName() { return name; } public void setName(String name) { this.name = name; } //Construction method public Student(String name) { this.name = name; } //Parameterless constructor (add a parameterless constructor as long as a class is a parent class) Student(){ } }
package com.bjsxt.abstractClass; public class Test { public static void main(String[] args) { //Student s =new Student("ddd"); Abstract classes cannot create objects Student s = new SxStu();//A parent class reference points to a child class object s.study(); s.exam(); } } class SxStu extends Student{ @Override public void study() { System.out.println("study hard!!!"); } @Override public void exam() { System.out.println("100 points!!"); } }
Key points of use
- Classes of abstract methods can only define abstract classes
- Abstract cannot be instantiated, (abstract class) cannot use new to create objects
- Abstract classes can contain properties, methods, and construction methods. However, the constructor cannot use a new instance and can only be called by subclasses
- Abstract classes can only be used to inherit
- Abstract methods must be implemented by subclasses
Implementation of interface
The essence of an interface is a specification, a set of rules defined, and the essence of object-oriented
The difference between the three classes
- [] common class: concrete implementation
- [] Abstract Class: concrete implementation, specification (abstract method)
- [] interface: Specification (jdk8 later special methods can be added)
Detailed description of interface
- [] access modifier: can only be public or default
- [] interface name: use the same naming mechanism as the class name
- [] extensions: interfaces can inherit from multiple sources
- [] constant: the attribute in the interface can only be a constant, which is always public static final. It can be written without writing
- [] method: the method in the interface can only be public abstract. If omitted, it is also public abstract
main points
- [] subclasses implement the specifications in the interface through implements
- [] the interface cannot create an instance, but it can be used to declare the variable type of the reference object
- [] if a class implements an interface, it must implement all methods in the interface, and these methods can only be public
- [ ] jdk1. Before 8 (excluding 8), the interface can only contain static constants, abstract methods, ordinary attributes, construction methods and ordinary methods
- [ ] jak1. After 8 (including 8), the interface contains ordinary static methods and default methods (extension methods)
package com.bjsxt.testInterface; /** * This is the interface of an aircraft */ public interface Volant { /** * Indicates the highest altitude of the aircraft on the earth, in kilometers */ /*public static final */ int MAX_HIGHT = 100; /** * Aircraft method, aircraft can take off */ /* public abstract */void fly(); /** * The aircraft can be stopped if hovering in the air or on the ground */ void stop(); } /** * Kind interface */ interface Honest { void helpOther(); }
package com.bjsxt.testInterface; public class SuperMan implements Volant,Honest{//All methods in the interface must be implemented, separated by English commas @Override public void fly() { System.out.println("Fly sideways"); } @Override public void stop() { System.out.println("Stand still"); } @Override public void helpOther() { System.out.println("where? call,Where to fly"); } public static void main(String[] args) { SuperMan m1 =new SuperMan();//Or write Volant m1 =new SuperMan m1.fly();//Without modification, fly() belongs to the Volant class m1.helpOther();//Here, you need to turn strongly to honey H = (honey) M1; } }
Default method
The difference between the default method and the abstract method is that the abstract method must be implemented, and the default method is not. As an alternative, the interface can provide the implementation of the default method, so the implementation class of this interface will inherit this method
interface A{ default void moren(){//default must be added System.out.println("I'm the interface A Default method in!"); } } class Test_A implements A{ @Override public void moren() { System.out.println("Test_A"); } } public class Test { public static void main(String[] args) { A a =new Test_A(); a.moren(); } }
Static method
If the same static method is defined in the subclass, it is my completely different method. It is directly subordinate to the subclass and can be called directly through the subclass name
public class Testjing { public static void main(String[] args) { B.staticMethod(); Test_B.staticMethod(); } } interface B{//The interface belongs to a special class public static void staticMethod(){ System.out.println("A.staticMethod"); } } class Test_B implements B{//Create subclasses public static void staticMethod(){ System.out.println("Test_B.staticMethod"); } }
Interface multi inheritance
interface B{ void test0b(); } interface C{ void test0c(); } /**Interface can inherit more than one, and interface D inherits B and C*/ interface D extends B,C{ void test0d(); } public class Test0 implements D{ @Override public void test0b() { } @Override public void test0c() { } @Override public void test0d() { } }
String class and constant pool
- Global String constant Pool
- Class Constant Pool
- Runtime Constant Pool
String equality judgment (generally judge whether the string values are equal in the future, using equals())
public class Test1 { public static void main(String[] args) { String str1 =new String("abcdef"); String str2 ="abcdef"; System.out.println(str1==str2); System.out.println(str2.equals(str1));//Compare whether our two string objects are the same } }
Common methods of String class
char charArt(index) // Returns the index character in the string boolean equals(String other) //If the string is equal to other, return true; otherwise, return false boolean equalsIgnoreCase(String other)//String and other (ignore case) return true, otherwise return false int indexOf(String str) //Returns the position of str in the string index from the beginning. If str is not found, return - 1 lastIndexOf(String str) //Returns the position of str in the string index from the tail. If it is not found, it returns - 1 int length()// Returns the length of the string String replace(char oldChar,char newChar)//Returns a new string, replacing boolean starWith(String prefix) //The judgment string starts with prefix and returns true. Otherwise, it returns false boolean endWith(String prefix) //If the judgment ends with prefix, return true; otherwise, return false String subsring(int beginIndex)//Returns a new string from beginIndex to the end of the string String substring(int beginIdex,int endIdex) //Returns a new string from beginIndex to endIndex-1 String toLowerCase() //Returns a new string, changing all uppercase of the original string to lowercase String toUpperCase() //Returns a new string, changing all lowercases of the original string to uppercase String trin()//Returns a new string, removing the leading and trailing spaces
//give an example public class test03 { public static void main(String[] args) { System.out.println("abcdef".charAt(5));//f System.out.println("abcdef".equals("abcdef"));//true System.out.println("ab".equalsIgnoreCase("AB"));//true System.out.println("abcde".indexOf("cd")); //2nd place System.out.println("abcde".lastIndexOf("d"));//3rd place System.out.println("abcde".length());//5 System.out.println("abcde".replace("bc","BC"));//aBCde System.out.println("abcde".startsWith("bc"));//false System.out.println("abcde".endsWith("de"));//true System.out.println("abcde".substring(1));//bcde System.out.println("abcde".substring(2,4));//cd System.out.println("abcde".toUpperCase());//ABCDE System.out.println("aBCDe".toLowerCase());//abcde System.out.println(" a b ".trim());//a b } }
Inner class
An inner class is a definition that places one class inside another.
Internal class is just a compile time concept. Once compiled successfully, it will become two completely different classes.
Functions of internal classes:
Internal classes provide better encapsulation, which can only be accessed directly by external classes, and other classes in the same package are not allowed to access directly.
Internal classes can directly access the private properties of external classes. Internal classes are treated as members of other external classes, but external classes cannot access internal classes
//Non static inner class //External class public class Outer1 { private int age = 10; private void show() { System.out.println("I want you to look good"); } //Inner class public class Inner1 { private String name = "tom"; private int age = 20; public void showInner() { System.out.println("Inner.showInner"); System.out.println(age); System.out.println(Outer1.this.age);//When the external class attribute and the internal class attribute have the same name, you can use: outer This member name show();//Inner classes can use members of outer classes directly } } public static void main(String[] args) { Outer1.Inner1 inn01 = new Outer1().new Inner1(); inn01.showInner(); //Another way of writing Outer1 out2 = new Outer1(); Inner1 inn02 = out2.new Inner1(); inn02.showInner(); } }
//Static inner class class Outer2 { private int a =10; private static int b =20; //Equivalent to a static member of an external class static class Inner{ public void test(){ // System.out.println(a); // Static inner classes cannot access external non static ordinary properties System.out.println(b);//Static inner classes can access static properties of outer classes } } } public class jingtai { public static void main(String[] args) { //External class name through new Internal class name () to create an internal object Outer2.Inner inner =new Outer2.Inner(); inner.test(); } }
//Anonymous Inner Class //Anonymous inner class test public class TestAnonymousInnerclass { public void test(A a){ a.run(); } public static void main(String[] args) { TestAnonymousInnerclass tai =new TestAnonymousInnerclass(); tai.test(new AA()); tai.test(new A() { @Override public void run() { System.out.println("TestAnonymousInnerclass.run"); } }); } } //There are names that can be used repeatedly class AA implements A{ @Override public void run() { System.out.println("AA.run"); } } interface A{ void run(); }