This is the third day of my participation in Gwen Challenge
Java as a pure object-oriented language, it is necessary for us to understand the basic knowledge of object-oriented.
Object orientation has four characteristics: abstraction, encapsulation, inheritance and polymorphism. There are also a lot of people think is the three characteristics, not including abstraction, but I think abstraction is the most core characteristics of object oriented thought, the other three characteristics are nothing more than the realization or expansion of abstraction this feature.
I’ve summarized what each of these four features solves in the object-oriented world, and I’ll start with abstractions:
- Abstraction: Resolves the problem of model definition.
- Encapsulation: Solves the problem of data security.
- Inheritance: Addresses code reuse.
- Polymorphism: solved the problem of program expansion.
Abstract is the core characteristic of object orientation. Good business abstraction and modeling analysis ability are the foundation of subsequent encapsulation, inheritance and polymorphism.
Abstract in object – oriented thinking can be divided into induction and deduction.
Induction is a logical thinking process that normalizes the common features of a class of objects from concreteness to essence, from individuality to generality. For example, we take the living things that we see, like elephants, tigers, pigs, that move, and we categorize them as animals.
Deduction is a process of gradually visualizing objects from essence to concrete, from generality to individuality. Like from creatures to animals, from animals to birds. The result of deduction does not have to be a concrete object, but it can also be an abstract result like a bird, so deduction is still abstract thinking rather than concrete thinking.
The Object class in Java is the default parent of any class and is an abstraction of everything. This is what we say: everything is an object.
Taking a look at the source code for the java.lang.Object class, we can basically see the common characteristics of objects in the Java world.
GetClass () says who the object is, toString() is the name card of the object, Clone () is the way to multiply the object, Finalize () is the way to destroy the object, hashCode() and equals() are the ways to determine whether the current object is equal to other objects. Wait () and notify() are ways of communicating and collaborating between objects.
The definition of a class
In addition to the classes provided in the JDK, we can also define classes based on abstractions from our own business scenarios.
Let’s look at how classes are formed in Java syntax.
The following is an overview chart, which we introduce.
Let’s focus first on the yellow block, which in Java is called a class.
Just like a thing has properties and abilities, people have names, people can eat. This corresponds to variables and methods in Java Class, the red and purple blocks.
Variables are divided into member variables, static variables and local variables, and methods are divided into constructors, instance methods and static methods.
For example, if there were only 100 pieces of bread in the world, and production had stopped, and only two people could eat the bread, we could describe the process and the situation of the bread for the two people in the following code.
package cn.java4u.oo;
/ * * *@authorThe snail *@fromPublic number: snail Internet */
public class Person {
/** * [member variables] need to be instantiated and used, each instance has its own space, through the object. Member variable name access * name */
String name;
/** * [static variable] uses static, does not need to instantiate, each instance shares the same space, through the class name. The static variable name accesses * quantity of bread */
static int breadNum;
/** * [method] * eat a loaf of bread **@paramNum the number of loaves to eat */
void eatBread(int num) {
// num is [local variable]
breadNum = breadNum - num;
System.out.println(name + "吃了 " + num + "One loaf of bread, all the bread left in the world." + breadNum + "A!");
}
/** * [constructor] * argument is null */
public Person(a) {}/** ** *@paramName This is the constructor input parameter, related to the member variable */
public Person(String name) {
this.name = name;
}
/** * [static method] */
static void testStaticMethod(a) {
// Use the constructor to initialize the snail
Person woniu = new Person("Snail");
// Use the constructor to initialize a person named White
Person xiaobai = new Person("White");
// Suppose there were only 100 breads in the world and production had stalled
Person.breadNum = 100;
// The snail eats five loaves
woniu.eatBread(5);
// Xiao Bai eats six loaves
xiaobai.eatBread(6);
// Prints the values of member and static variables
System.out.println(woniu.name + "And" + xiaobai.name + "When you're full, there's nothing left." + Person.breadNum + "Bread!); }}Copy the code
variable
We first define a class named Person to represent a Person, and then a member variable named name to represent the name of the Person. Member variables are also called instance variables. The feature of instance variables is that each instance has independent variables, and the variables with the same name between each instance do not affect each other.
Secondly, a static variable breadNum was defined to represent the amount of bread. The static variable was decorated with static. A static variable is not the same as a member variable; it is shared by all instances.
methods
Then define a return value is empty, only one input parameter method eatBread(int num), method input parameter num as a local variable to participate in the internal operation, through its operation, the value of the static variable breadNum to update, and print a line of operation information. The syntax structure of the method is as follows:
Modifier returns type method name (method argument list) {method statement;returnMethod return value; }Copy the code
In addition, I’ve defined a constructor for Person, and you’ll notice that the difference between a constructor and an instance method is that it doesn’t return a value, because its purpose is purely to initialize an instance of an object, and it’s used with new, so its method name is the class name, and its input parameters are all related to member variables.
At this point, you can see that the return value of a Java method is not that important, or even none! Yes, Java method signatures contain only names and parameter lists, which are the JVM’s unique index to identify methods. They do not contain return values, nor do they contain modifiers or exception types.
Note that any class has a constructor, and even if you don’t write it in your code, Java will generate a constructor with no arguments by default when compiling the class file. But as long as you manually define the constructor, the compiler will not regenerate. That is, if you define only one constructor with arguments, the compiled class will not have a parameter-free constructor.
The final static method is called testStaticMethod. Inside the method, we call the constructor using new syntax to initialize the snail and the small white Person object. These two objects are instances of the Person class. They have separate Spaces, and the name member variable can only be used after being instantiated. Member variable name access.
Next we go through person. breadNum, which is the class name. Static variable name to update the number of buns. You’ll notice that the static variable breadNum doesn’t need to be instantiated because, as far as this variable is concerned, each instance of Person shares the same space. This means that every instance change affects the value of this variable.
We then influence the number of buns by calling the method eatBread and passing it as an argument.
package cn.java4u.oo;
/ * * *@authorThe snail *@fromPublic number: snail Internet */
public class MainTest {
public static void main(String[] args) {
// Static method, by class name. Static method name accessPerson.testStaticMethod(); }}Copy the code
Finally, we define a new entry function that triggers the call, with a class name like Person.TestStaticMethod (). Static method names are used to access static methods.
Abstract classes and interfaces
An abstract class, as its name suggests, abstracts things of the same class, usually including abstract methods, instance methods, and member variables. The relationship between the abstract class and the abstract class is IS-A, which should conform to the Richter’s substitution principle, that is, all the behaviors of the abstract class are applicable to the abstract class. For example, the elephant is an animal, and it can do everything that animals can do. The code definition is also simple, adding the abstract modifier to the class and abstract methods.
package cn.java4u.oo;
/** * abstract class **@authorThe snail *@fromPublic number: snail Internet */
public abstract class AbstractClass {
String name;
/** * instance method **@return name
*/
public String getName(a) {
return name;
}
/** * abstract method - operation **@returnResults the * /
public abstract String operate(a);
}
Copy the code
If an abstract class has only one abstract method, it equals an interface. Interfaces are required to be implemented by ordinary classes. When interfaces are implemented, they embody can-do relations, which express the capabilities of objects. Birds have the ability to fly, spaceships have the ability to fly, so you can pull out the ability to fly, there is a separate abstract method. The code definition is also simple, with the class keyword replaced by interface.
package cn.java4u.oo;
/** * can fly **@authorThe snail *@fromPublic number: snail Internet */
public interface Flyable {
/ * * * * /
void fly(a);
}
Copy the code
The inner class
In a Java source file, you can define only one public class whose class is exactly the same as the file name. If you want to define another class in a file, which is also supported in object orientation, it is an inner class.
The inner classes are divided into the following four categories:
- Static inner class:
static class StaticInnerClass {}
- Member inner class:
private class InstanceInnerClass {}
- Local inner class:
class MethodClass {}
Is defined inside a method or expression - Anonymous inner class:
(new Thread() {}).start();
Example code is as follows:
package cn.java4u.oo.innerclass;
/** * Inner class demo **@authorThe snail *@fromPublic number: snail Internet */
public class InnerClassDemo {
/** * Member inner class */
private class InstanceInnerClass {}
/** * static inner class */
static class StaticInnerClass {}
public static void main(String[] args) {
// Two anonymous inner classes
(new Thread() {}).start();
(new Thread() {}).start();
// Method inner class
class MethodClass {}}}Copy the code
The resulting class file looks like this:
We’ll see that any inner class of any type is compiled to produce a separate.class file, except that the inner class file is named after the outer class by $, and if the inner class is anonymous, it is identified by a number.
Class relationships
Relationship refers to the state in which there is no one direction or interaction or influence between things.
Classes and relationships between classes fall into six categories:
- Inheritance: extends (is – a)
- Implementation: implements (can do)
- Composition: class is a member variable (contains-a)
- Aggregation: Class is a member variable (HAS-A)
- Dependencies: one-way weak relationships (using class attributes, class methods, as method inputs, as method outputs)
- 1. A relationship of dependence that is equal to each other (links-A)
serialization
Data objects in memory can be persisted and transmitted over the network only if they are converted to binary streams.
The process of converting data objects into binary streams is called Serialization of objects.
The process of restoring a binary stream to a data object is called Deserialization.
A common serialization usage scenario is data transfer for RPC frameworks.
There are three common methods of serialization:
- Java native serialization. Features are good compatibility, do not support cross-language, general performance.
- Hessian serialization. Features cross-language support and high performance.
- JSON serialization. Features good readability, but security risks.