Notes on object-oriented programming
There are two important concepts in object-oriented
- Class is an abstract concept that has something in common -- such as human beings
- Object is a concrete concept and an instance, just like Kobe
- Kobe is an object, and professional basketball players are a class
There are properties and methods in a class, collectively referred to as members
Member method
-
Member methods must be called by objects (instances)
-
The member method wants to be an object's action, such as Kobe playing basketball
Discuss the mechanism of parameter passing of method
- Parameters are divided into formal parameters and arguments
- The formal parameter can be regarded as a variable
- An argument is a concrete data
- A formal parameter is an interface between a method and the outside world
-
The level of each member method is the same. Methods cannot be defined in methods
-
Description of assignment
1. If it is a basic data type, copy the data directly 2. If it is a reference data type, the address in the heap will be copied directly 3. The basic data type is independent and the reference data type is shared
Method recursion is very important!!! (incomplete)
There is a lot of code missing here to supplement
Comparison of method overloading and rewriting
-
For method overloading, the method name is the same, the parameter list type is different, and others are free
-
***There are many requirements for rewriting * * *
1. First, the method name must be the same, and the parameter list type must be the same 2. The return value type is the corresponding or its subclass 3. You cannot throw more exceptions 4. The access modifier range cannot be reduced 5. ***most important of all!!!!!!*** 6. Rewriting must occur in two classes that have an inheritance relationship 7. Overloading occurs in this class
Variable parameter (formal parameter)
- That is, the number of parameters in the parameter list is uncertain
- Its essence is an array
- The argument passed in can be a * * * array***
package OverJava; public class Unkown { public static void main(String[] args) { say(1,2,4,5,6,7,8,9); } public static void say(int... nums) { for (int i = 0; i < nums.length; i++) { System.out.println("The first"+(i+1)+"Values are"+nums[i]); } } }
be careful
- Variable parameters can be put together with ordinary type parameters, but variable parameter types must be at the end
- Each method must have only one variable parameter
Scope
Variables in java are divided into global variables (attributes) and local variables
- Local variables cannot have modifiers
- Global variables can be modifiers
- Local variables are in a method and can only be used by that method
- Global variables can be called in this class or in other classes
- Global variables have default values and local variables do not
- Global variables die as objects are created
- Local variables are created and die with the execution of his code block
constructor
Used to initialize instances
- Is a special method
- The method name is the same as the class name and has no return value
- Creating an object is an automatic call constructor
this keyword
- this refers to the current object
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-vjYVmHmr-1636375616845)(C:\Users \ story and wine \ appdata \ roaming \ typora user images \ image-20211106112346109. PNG)]
Remember that this is the current object
this() calls other constructors of this class
Package package
His essence is a folder
It is convenient to manage classes with the same name in different packages
Access modifier
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-gWP4sdYL-1636375616848)(C:\Users \ story and wine \ appdata \ roaming \ typora user images \ image-20211106113346244. PNG)]
For a class, it has only public and default modifiers
Again, local variables cannot have modifiers
Three characteristics of object oriented
- encapsulation
- inherit
- polymorphic
encapsulation
- Is to privatize attributes and provide public methods for protection
- Generally, there are getXXX(); setXXX();
inherit
- It is to abstract some common methods and properties in many classes and put them in a class. Then this class is called the parent class
- Keyword extends
- java only supports single inheritance
- The subclass inherits all the methods and properties of the parent class, but the private ones cannot be accessed directly. They can be accessed through public methods
- Subclasses must call the constructor of the parent class to initialize the properties and methods of the parent class
- Creating a subclass object is the parent class. The constructor will first call the member of the parent class to initialize the member of the subclass
- However, the object still has only one subclass, and only the methods and properties of the parent class are initialized in the subclass object
Look at the picture
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-tJIKYORB-1636375616852)(C:\Users \ story and wine \ appdata \ roaming \ typora user images \ image-20211106115246776. PNG)]
super keyword
super keyword is used to call the properties and methods of the parent class, but certain access permissions must be observed
super()
- Used to call the constructor of the parent class
- In the constructor of the subclass, there is a parameterless constructor super() by default; And on the first line
Comparison between super and this
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-3onrz02-1636375616855) (C: \ users \ story and wine \ appdata \ roaming \ typora user images \ image-20211106120549440. PNG)]
In fact, the reason is that in the object instance, the members of the parent class and the members of the child class are independent of each other
polymorphic
What are polymorphic States
- The method is polymorphic
-
The rewriting and overloading issued reflect polymorphism (different objects with the same method name have different calling effects, and different parameters have different effects)
-
Polymorphism of parameters
1. The formal parameter type is the parent type ***Argument types can be subclasses*** 2. In essence, or upward transformation
- The most important thing is the polymorphism of * * * objects***
Polymorphism of objects
-
Objects are divided into compile type and run type
-
Compiler type is checked by the compiler. The compiler does not check the running type
-
Person person = new Student();//Student inherits Person
The compile type is Person and the run type is Student. The compiler will not check Student when checking Person
- In fact, upward type conversion is the automatic conversion of basic type data
- Downward type conversion is the casting of basic type data
Person person = new Student();//Student inherits Person Student student = (Student) person;// Downward transformation
Talk about my understanding of parent class reference pointing to child class objects
- First, the compiler checks whether the properties and methods of the parent class in the code are correct when it only sees that the compiled type is the parent class
- That's why you can't point to methods unique to subclasses with parent class references
- If you want to use methods unique to subclasses, you can point to objects with subclass type references
- As for why I understand this (drawing on the basic data types), it may be the space opened in memory or something else is a little different
- Use instanceOf() to determine whether the type or its subclass is
Person person = new Student();//Student inherits Person Student student = (Student) person;// Downward transformation student instanceOf(Person);//true student instanceOf(Student);//true Object obj = new Object(); obj instanceOf(Person);//false
Talk about Object
==The difference between and equals
- ==Is a comparison operator and equals() is a method
- ==You can compare both basic data types and reference data types
- The basic data type depends on whether the values are equal
- The reference data type also depends on whether the values are equal, but the value is an address, so it depends on whether it is a common object
equals()
- It is a method of Object, which can only be used to judge the reference data type
- If it is not rewritten, it is to judge whether the addresses of the reference data types are consistent and whether they are the same object
- If it is rewritten, it is to judge whether the content is consistent, such as in the wrapper class and String
Here we briefly talk about hashCode, toString and finalize
- hashCode replaces the address of the object with a hash code value
- The toString method is the hexadecimal of the full class name + @ + hash value
- The finalize method is that when the JVM considers it a garbage object, it calls its finalize method before destroying it
Method of breakpoint debugging (incomplete)
Here later to add!!!
Class variables and class methods (static methods and static variables)
- Sometimes we want to share some data and methods in the same class, and class variables play a role
- Class variables are static and are decorated with (static)
Look at the picture
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ma4POLVr-1636375616856)(C:\Users \ story and wine \ appdata \ roaming \ typora \ typora user images \ image-20211106152449087. PNG)]
- About accessing class variables
- Use class name. Class variable name
- You can also use object name. Class variable name
- Class variables belong to classes, so they can be accessed without objects
- Class variables are shared by all objects of this class, while instance variables are exclusive to each object
- Class variables are initialized when the class is loaded. They will be loaded when the class is loaded and die when the class dies
The idea of class method is similar to that of class variable
- Class methods are generally used as tool classes, which can be used without creating objects
- Such as Math.sqrt();
Comparison of class methods and member methods
- Class methods and ordinary methods are loaded with the loading of classes, and the structure information is stored in the method area
- Class method cannot have this and super
- Class methods can only access static methods and static variables
- Member methods can access both static and non static methods
- They all have to comply with access rights
Explain the main() method
-
public static void main(String[] args){}
-
The main() method is called by the JVM. The JVM must not be together with the main() class file you wrote, so use public
-
The jvm calls without creating objects, so it is static
-
Void calls the main() method and does not expect a return value, so it is void
-
String [] is a string array that holds Java commands and parameters passed to the running class
Some notes
- The main method can directly call the static methods and static variables of this class, but cannot use member methods and member variables
- To use the member methods and member variables of this class, you must create an object
Code block
- The modifier of a code block can only have static
- The code in the code block can be any code
- The code block is a supplement to the constructor and can be used for initialization
- For example, many of the same statements in each constructor can be extracted into the initialization block to improve code reusability
- The data called by the code block takes precedence over the constructor
- The static code block is executed only when the class is loaded and only once. If it is a normal code block, it is called every time the object is created
- Here is a description of when the class is loaded (very important!!!)
- Create object instance
- The parent class of the object instance that uses the child class will also be loaded
- When using static members of a class
- Ordinary code blocks are implicitly called when creating instances
- If only static members are used in a normal code block, the normal code block does not execute
The call order in a class when creating an object
- Static code blocks and static attribute initialization have the same priority. They exist at the same time and are initialized in their order
- The priority of common code blocks and attribute initialization is the same. If they exist at the same time, they will be initialized in their order
- Finally, the construction method
Let's look at the internal structure in the constructor (an understanding)
class A { public A() { //Execution requirements are hidden here //(1) super(); //(2) Call normal code block //Then execute the content in the constructor } }
Call order in inheritance relationship
- Initialization of static code blocks and static variables of the parent class
- Static code block and static variable initialization of subclasses
- Normal code block and member variable initialization of the parent class
- Constructor of parent class
- Initialization of ordinary code blocks and ordinary member variables of subclasses
- Constructor of subclass
Expansion - singleton mode (incomplete)
final keyword
Final means final in Chinese
- final can modify class attribute method local variables
- It's like only final (my current understanding may not be comprehensive)
- A class decorated with final cannot inherit
- final modified methods cannot be overridden
- Variables decorated with final cannot be changed
abstract class
Some factors may make the method uncertain
- This requires an abstract method
- Classes containing abstract methods must be abstract methods
- The keyword is abstract
- Abstract method has no method body
public abstract void say(); // {} having curly braces means having a method body
-
Abstract classes cannot be instantiated (besides, instantiation has no meaning, and the methods in them are empty)
-
Abstract classes can have no abstract methods, but * * * with abstract methods, they must be abstract classes***
-
Abstract method is essentially a class. It can have non abstract method constructors (I don't quite understand) static properties
-
If a class inherits an abstract class, it must override all the abstract methods in it
-
Abstract methods cannot be modified by private final static (because it violates rewriting)
Here is a best practice for abstract classes (to be added!!!)
Interface
An interface is the encapsulation of some unimplemented methods. When a class is to be used, it is rewritten according to the specific logic
Basic grammar
interface S { //attribute //Abstract method (can be modified without abstract) } class A implements S { //Own members //The method of S interface must be implemented }
Interfaces are abstract classes. Before jdk7, methods in interfaces could not have method bodies
After jdk8, there can be static methods and default methods. In other words, there can be specific methods implemented in the interface
The interface can regulate some standards (now I'm Xiaobai and don't quite understand the magic of the interface)
be careful
- Interfaces cannot be instantiated (because interfaces are more abstract classes)
- The methods in the interface are all public, which can not be modified by abstract
- A common class implementation interface must implement all abstract methods
- Abstract classes can implement interfaces without implementing methods of interfaces
- A class can have multiple interfaces
- The attribute of an interface can only be final and public static final
- Interfaces cannot inherit from other classes, but they can inherit from other interfaces
- Interface modifiers can only be public and default
Difference between interface and inheritance
Here is a brief explanation
Inheritance satisfies is xxx
The interface satisfies like xxx
I'm also a little white. I don't have any code accumulation and don't understand it very well
- For the interface, it is more flexible and can be better standardized and extended
- Inheritance mainly solves the reusability and maintainability of code
Interface polymorphism (to be supplemented)
Briefly, the reference of an interface can point to the class that implements the interface
You can think of it this way. An interface is just a class more abstract than an abstract class (I don't know how to understand it in essence)
Therefore, you can use the reference of the interface to point to the object of the class that implements the interface
This is a simple explanation first, which will be supplemented later
Inner class
Class, the inner class of the constructor code block of the five member attribute (field) method
Internal classes are divided into
- Local inner class
- Anonymous inner class (very important!!!)
- Member inner class
- Static inner class
To sum up, it seems that only methods cannot be nested
Local inner class
The local inner class is in a local location of the external class, such as in a method, and has a class name
- Local internal classes can access all properties of external classes, including private ones (in fact, it is well understood that the essence of local internal classes is that external classes can access private members in the current class)
- The access modifier cannot be added, but the final keyword can be added (the local internal class is equivalent to a local variable)
- His scope is only in the method or code block that defines him
- Local internal class access external class members (direct access)
- The external class accesses the local internal class (accessed by creating an object, but * * * still has to be within its scope * * *)
- Other external classes cannot access local internal classes
- If the external class and the local internal class have the same name, follow the proximity principle. If you want to access the members of the external class, use (external class name. this. Member)
The code is missing here
Anonymous inner class (very important!!!)
- Nature is still a class
- Inner class
- Or an object
- This class has no name
//Basic grammar //new class and interface name (parameter list) {Class body}; // No fewer semicolons
Other considerations are the same as local inner classes
Code demonstration
package OverJava; public class UnName { public static void main(String[] args) { //Demonstrates three anonymous inner classes //abstract class Animal dog = new Animal(){ public void move() { System.out.println("The dog is moving"); } public void eat() { System.out.println("The dog is eating bones"); } public void sleep() { System.out.println("The dog is sleeping"); } }; dog.eat(); dog.move(); dog.sleep(); System.out.println("Class of dog object"+dog.getClass()); //General class Father father = new Father("jack",39){ }; System.out.println(father.info()); System.out.println("father Class of object"+father.getClass()); //Interface Usb meizuUsb = new Usb(){ @Override public void workStart() { System.out.println("Meizu mobile phone interface starts working"); } @Override public void workEnd() { System.out.println("Meizu mobile phone interface stops working"); } }; meizuUsb.workStart(); meizuUsb.workEnd(); System.out.println("meizuUsb Class of object"+meizuUsb.getClass()); } } //This is an abstract class abstract class Animal { public abstract void move(); public abstract void eat(); public abstract void sleep(); } //This is a common class class Father { private String name; private int age; //constructor public Father(String name, int age) { setName(name); steAge(age); } //setter and getter public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void steAge(int age) { if (age <= 0) { System.out.println("Your age is illogical(Has been assigned to the default value)"); this.age = -1; } this.age = age; } public String info() { return getName() + "Hello,"+getAge()+"This is your age"; } } //This is an interface interface Usb { void workStart(); void workEnd(); }
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-bhLLupkr-1636375616859)(C:\Users \ story and wine \ appdata \ roaming \ typora \ typora user images \ image-20211107142735123. PNG)]
Anonymous inner classes are used to simplify development (pay attention to code accumulation)
Best practices for anonymous inner classes
Passing directly as an argument is concise and efficient (it may not feel good for me now)
Code example
package OverJava; public class UnNameGood { public static void main(String[] args) { Master master = new Master(); master.feed( new Animal_("min-hashing "){ @Override String eat() { return this.name +"Eat bones"; } } ); } } //Define a class class Master { public void feed(Animal_ animal)//There are no parameters here { System.out.println("The master is feeding"+animal.eat()); } } //Define an abstract class (animal) abstract class Animal_ { String name; public Animal_(String name) { this.name = name; } abstract String eat(); }
package OverJava; public class BestUnName { public static void main(String[] args) { Phone pandaer = new Phone("PANDAER", "17 Gray degree"); pandaer.alarmclock( new Bell(){ @Override public String ring() { return "The little lazy man got up"; } } ); } } //Analog alarm //Define an interface interface Bell{ String ring(); } //Define a mobile phone class class Phone { String name; String color; String masterName = "Story and wine"; //constructor public Phone(String name, String color) { this.color = color; this.name = name; } //Alarm clock method public void alarmclock(Bell bell) { System.out.println(color+"of"+name+"The alarm clock of the mobile phone makes a sound:"+bell.ring()+",Wake up"+masterName); } }
Member inner class
The internal class of a member is defined at the position of the external class member, and cannot be decorated with static
- You can directly access all members of an external class, including private
- Any access modifier can be added because its status is a member (which can be regarded as a member variable and a collection of member variables)
- Since it is a member, its scope is in the whole external class;
External class ----------- internal class: the object to create the internal class is accessed again
Internal class ------------ external class: direct access, simple
Other external classes can also access member internal classes:
- You can write a method in an external class to return an instance (object) of an internal class
- You can also create objects directly
Outer.InerClass iner1 = new Outer().new InerClass();
Code demonstration
package OverJava; public class InerClass { public static void main(String[] args) { Mater1 mater1 = new Mater1(); mater1.say(); mater1.say2(); } } //This is an external class class Mater1 { //The first way Outer outer = new Outer(); Outer.InerClass iner = outer.getInerClass(); //(the second way) Outer.InerClass iner1 = new Outer().new InerClass(); public void say2() { System.out.println("say2 Yes"); iner1.say(); } public void say() { iner.say(); } } //This is a class with member inner classes class Outer { String name; int age; class InerClass { public void say() { System.out.println("I said EDG fucking great!!!"); } } //Return an inert object in an external class (a way) public InerClass getInerClass() { return new InerClass(); } }
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-rfzc633h8-1636375616861) (C: \ users \ story and wine \ appdata \ roaming \ typora user images \ image-20211107152939927. PNG)]
(the picture above is not particularly accurate. I'm Xiaobai, too)
Static inner class
- The static inner class has a static modifier on the member position of the outer class
- He can still add access modifiers. After all, his status is a member
- Since it is a member, of course, its scope is all of the external classes
- Static internal classes can directly access static variables and methods of external classes, but cannot directly access member methods and variables of external classes (through new objects)
External class ----------- static internal class: to create an object and then access it
Other external classes - static internal classes: there are also two methods
- The first is to create a method in the external class to return an object of a static internal class
- Second
Outer.iner iner1 = new Outer.iner();
My understanding: the constructor of a static internal class is equivalent to a static method, which can be called directly through the class name and method name, so external object instances cannot be created (the understanding is not necessarily accurate)
Code example
package OverJava; public class StaticInerClass { public static void main(String[] args) { OuterOther outerOther = new OuterOther(); outerOther.iner2.say(); System.out.println("========="); outerOther.iner3.say(); } } //This is an external class class OuterOther { //The first way to call a static inner class Outer2.Iner2 iner2 = Outer2.getIner2(); //The second way Outer2.Iner2 iner3 = new Outer2.Iner2(); } //Define a class with a static inner class class Outer2 { String name; static class Iner2 { static String name = "min-hashing "; public static void say() { System.out.println(name + "How do you do" ); } } public static Iner2 getIner2() { return new Iner2(); } }
Conclusion
The ability of code always fails
With a strong theory, we should also have enough practice
When you write code, you should concentrate on it
I don't have him, only my hand is familiar!!!
Understanding (not necessarily accurate)
Code example
package OverJava; public class StaticInerClass { public static void main(String[] args) { OuterOther outerOther = new OuterOther(); outerOther.iner2.say(); System.out.println("========="); outerOther.iner3.say(); } } //This is an external class class OuterOther { //The first way to call a static inner class Outer2.Iner2 iner2 = Outer2.getIner2(); //The second way Outer2.Iner2 iner3 = new Outer2.Iner2(); } //Define a class with a static inner class class Outer2 { String name; static class Iner2 { static String name = "min-hashing "; public static void say() { System.out.println(name + "How do you do" ); } } public static Iner2 getIner2() { return new Iner2(); } }
Conclusion
The ability of code always fails
With a strong theory, we should also have enough practice
When you write code, you should concentrate on it
I don't have him, only my hand is familiar!!!