Java basic knowledge points (classes and objects, methods, encapsulation, inheritance, polymorphism, abstract classes and interfaces)

One, class and object

1. What is a class? What is the object? What is the relationship between class and object?

A class is an abstract concept of a class of things. It does not refer to a specific thing, but extracts the characteristics of this class of things, and then forms a concept with a range of directions.

An object is a specific reference in a certain category, which represents a real concrete thing. The process of generating objects from a class is called instantiation.

A class is a collection or collective term for objects with the same properties and behaviors.

An object is an entity created by a class. The attributes and behaviors of this entity have been specified by the class. Without a class, you cannot create an object.

Entity class: existing in the real world

Functional test category: describes the logical relationship, the world is composed of categories and objects.

Class creation: attributes (nouns), methods (verbs).

Steps to simulate offline business online:
1. First classify: entity class
2. Use variables to represent their detailed information
3. Process data (assignment, value)

2. Unit test:

@Test (You can click to execute like the main method)
1. The method must be public.
2. It cannot have a return value or parameters
. 3. It cannot call each other with the main method.

To use unit testing, you need to do the following: you
need to put hamcrest-core-1.3.jar and junit-4.12.jar in the lib in the IDEA folder
into the lib folder created by the project and src in parallel, and then select Add as Library...

To use the Scanner method in the unit test, you need:
help "Edit Custom VM Options...
Add to the last line: -Deditable.java.console=true

3. The output is concise

%s means string %d means integer %f means decimal

System.out.printf("Hello everyone, I am %s, I am a %s, I am %d years old this year, my face value is %.2f, and the good value is %.3f," name, sex, age, yanzhi ,cute);

.2 means to keep two decimal places after decimals.
3 means to keep three decimal places after decimals

4. Class:

The actual parameter is the value assigned to the formal parameter.
Return value: the output of the method.
Parameters: the raw materials needed to enter the method.

Calling other methods in the main method:
1. Instantiate the object, and get a class object through the construction method (the virtual machine opens up the memory behavior).
2. Object calls methods.

All methods or properties modified by static belong to the power (usable) range of the class. What is
not modified by static is the usable range of the object

Second, the method

1. The composition of the method:

修饰符 返回值类型 方法名(参数类型 参数名1,参数类型 参数名2,......){
    
     
	执行语句
	1.方法的调用
	2.变量的操作:声明 赋值  修改
	3.程序结构:选择结构 循环结构……… 
	return 返回值;
}

2. Modifiers:

1. Access (call) permission modifier public is public, this project can be used. Private, only available for the current class.

2. Static modifier: static

3. Return value type:

1.void has no return value

2. There is a return value: return a basic type of data or reference type data (class, array)

4. Method name:

The first word is lowercase, and the first letter of the second and subsequent words is uppercase, consisting of letters, underscores, and numbers.

5. Parameters:

There can be none, or there can be. The declaration of the parameter is the same as the declaration of the variable. It only defines the type, takes the name, and does not assign the value.

1. The classification of parameters: formal parameters and actual parameters.

2. The relationship between formal parameters and actual parameters: actual parameters are assigned to the formal parameters

3. Keep the number of formal parameters and actual parameters consistent with the same type.

4. The scope of use of formal parameters: equivalent to the local variables declared in the method body

Extension: Deformable parameter group:
1. Declare method type... Parameter name
2. If other parameters are needed, put the deformable parameter group at the end
3. You can use the length attribute to get the number of
variable parameters 4. Variable parameters You can pass no value

Static belongs to the class, all objects are common, and there is a share.
For instance, each object has a separate copy.

6. Call:

Static is static, belongs to the class, and is called by the class name.
Instances, belonging to objects, are called through objects.
Note: Class names can only call static ones, and objects can call instance or static ones.

Public class Person{ int a=0;//The instance has multiple variables static int b=0; //There is only one static copy. psvm { sout (Person.b); sout(Person.a) wrong Person p1=new Person(); p1.b=6; p1.a=6; Person p2=new Person(); sout(p2.b) //6 so ut(p2.a);//10 } } Instance method: public void fun1(){} Static method: public static void fun2(){}













In the same
category : 1. The static method calls the static method class name. The static method (), the class name can be omitted.
2. Static method call instance method object name. Instance method ();
3. Instance method call instance method
1. This. Instance method () You can omit this (current object) 2. Instance object. Instance method ()
4. Instance method Call the static method class name. Static method () can omit the class name

In different classes:
1. In a static method, call a static method of another class. Class name. Static method ()
2. In a static method, call an instance method of another class. Object name. Instance method ()
3. Call another in an instance method Instance method object name of the class. Instance method ()
4. In the instance method, call the static method of another class. Class name. Static method ()

7. Construction method:

1. Each class comes with a no-argument construction method

2. The return value of the construction method and the method are duplicated, so omitted

3. Parameter construction: parameters are used to assign values ​​to member attributes

4. No-parameter construction
Refers to the member properties of the data type, the default value is
the object created by the null no-parameter construction, the properties are not assigned, only the default value.
Objects created with parameter construction also need to be assigned.

8. Overload:

The same class, the same method with the same name, different parameters,
different classes, different numbers of parameters, different types, and different orders.

Object array: User[] users={u1,u2,u3};
//Enhance for output: for(User u:users){ sout(u.name+”–”+u.age) }

The object array is used as the method parameter addAge(users); the
object can create variables to receive the value: Goods g=init();

Three, encapsulation and inheritance

1. Package:

Why encapsulate: concealment, security.

Encapsulation steps:
1. Private member properties (preceded by private)
2. Provide public get (getter) and set (setter) methods

//setter赋值
public void setSex(char sex){
this.sex=sex;
}

//getter get
public char getSex() { Return this.sex; }

Insert picture description here

2 bags:

Import package: import your own package and system package

The java.lang package is the core of the java language and it provides the basic classes in java. (The java.lang package belongs to the system package, the classes in this package do not need to be imported, such as System, String)

Insert picture description here

3. Access modifier:

The following figure: protected situation (protected): the subclass must be in the same package.

Insert picture description here
Access modifiers of the class:
Public: Open to the outside world
Default: the package is valid, and cannot be accessed outside the package-reflected in the construction method

Member access modifiers (member attributes and member methods)
Public: Public:
Protected: Protected, accessible to subclasses of the same package.
Default: can access in the same package.
Private: only valid in the current class

4.static and this keywords

All modified by static will be loaded with the loading of the class.
All instances will be loaded with
Static modification due to the creation of the object , belonging to the scope of the class, this represents the current object.
Static modifies member attributes and methods and code blocks

The meaning of this:
1. Represents the current object-appears in the instance method
2. Represents other construction methods-appears in the construction method, must be in the first line
Note: this cannot appear in a static method

5. Inheritance:

1. Extract the same properties and methods from multiple subclasses to form the properties and methods
of the parent class 2. Inheritance and use of members of the parent class (including member properties and member methods)

Extract common repeated codes and use inheritance to improve code reusability,

Let the relationship between the class and the class: extends

Inheritance is the only way to have an association relationship between two classes

The subclass construction method will call the parent class construction method by default.

Provides a prerequisite for polymorphism

Single inheritance is supported in Java: a subclass can only have one direct parent class

Multiple inheritance is not supported in Java

6. The difference between this and super:

this:
1. In the member method of this class, access the member variable of this class and access another member method of
this class 2. In the construction method of this class, access another construction method of this class

super:
1. In the subclass member method, access the parent class member variable and member method
2. In the subclass construction method, access the parent class construction method

The member variable and local variable of this class have the same name, distinguished by this,
and the member variable of this class and the variable of the parent class have the same name, distinguished by super

7. Rewrite (overwrite) and reload:

Overloading: In the same class, the method name is the same and the method parameters are different. Typical applications: parameterless construction and parameterized construction

Rewrite: the method of the subclass and the parent class with the same name.

The subclass method has the same name as the parent method, and the subclass method will override the parent method, which is called override (override). The premise is that the access permission of the subclass method must be greater than or equal to the access permission of the parent method

8.Final:

Modified variables are called constants, and their values ​​cannot be modified.
Modified methods cannot be rewritten to ensure safety and stability.
Modified classes cannot be inherited to prevent functions from being overwritten.

9. To make a class not inherited by other classes:

1. Modified with final

Constructor privatization

10. Inheritance summary:

Access modifier:
Public: the entire project
Default: the same package
Protected: the same package, the subclass can use
Private: the current class

Static: static, only one copy, belonging to the class, common to all objects
This: instance method-the current object this. Properties/methods, construction methods-other construction methods this ();
Super: instance method-the parent class object super .Parent class attribute/parent class method, construction method-parent class construction method this();

Inheritance:
1. The relationship between classes and classes: containment and attachment.
2. Extract the same attributes and methods and place them in the parent class, and let the subclass inherit and use it.
Method rewriting: covering
the method of the same name in the subclass and the parent class. The function
of the subclass is more powerful than that of the parent class.

Four, polymorphism

1. Override the equals method of the object class

1. The equals() method of the Object class :
compares whether two objects are the same object, if yes, it returns true. The
Object class is the parent class of all classes, and its equals method will naturally be inherited by all classes. There is a subclass String pair The equals method has been overridden (overridden) to give it new functions

2. Operator ==
simple data type or constant value, compare values ​​directly.
Reference type, compare whether it is the same object.
(1) The equals() method of the Object class is indistinguishable from the two =
(2) Java.lang.String rewrites the equals() method, turning the judgment of the equals() method into a judgment of its value
(3) When there is a special Requirements, if you think that the attributes are the same as the same object, you need to rewrite equals()

Case:
1. How to rewrite the equals method when analyzing the String class.
2. Override the equals method in the Pet class

Summary:
1. Basic data type data value can only use two =
2. For reference data type, two = and the equals method of Object are the same.
3. Because the String class rewrites the equals method of the parent class Object, the only difference between == and equals is:
Insert picture description here

2.instanceof

The instanceof operator in java is used to indicate whether an object is an instance of a specific class at runtime. instanceof returns a boolean value to indicate whether the object is an instance of this particular class or its subclass.
Format: object instanceof class
Usage analysis:
formal parameters and actual parameters and the type on the right are
mainly to see whether the actual parameter object is Belongs to the right type

3. Polymorphism

After encapsulation, we can use two methods to assign values ​​to object properties, the set method and the parameterized construction.
When to use set and when to use parameterized construction.
Set can repeatedly modify the attribute value after creating the object. The parameterized construction is to assign values ​​to attributes at the same time as the object is generated, and the same object can only be used once.

1. What is polymorphism?
//Assign the instantiated object of the subclass to the reference type of the parent class
inherit Fu f=new Zi(); Pet p=new Dog(); Pet p=new Penguin();
rewrite fa();
multiple states Polymorphism = inheritance + rewrite

2. Case understanding:
1. Use polymorphism to realize pets to see a doctor
. 2. Use polymorphism to realize pet feeding.
3. Pet donation system

Application:
1. The parent class is used as the method parameter (the most common use of polymorphism).
Case: Both dogs and penguins have methods to see a doctor. If the health value is less than 50, the owner will take them to see a doctor.
2. The parent class as the return value of the method

Example: donating animals

Fu f=new Zi();
parent class—static method subclass—instance method

In polymorphism:
call the instance method of the subclass, and the subclass overrides the instance method of the parent class with the same name.
Call the static method of the subclass, and it will never fall.
Each method has a constant pool.

Up-casting and down-casting

The understanding of polymorphic grounding: the parent class is used as the formal parameter, and the subclass type is used as the actual parameter.

Upward transformation: ---- Subclass to parent class
Pet a = new Dog ();
parent class subclass
Object aa = a;

Downward transformation:-First go up, then go down, and it can't be lower than before.
Dog b=(Dog)a;
Dog e=(Dog)aa;

Rewrite equals to
rewrite the comparison rules to determine whether two students (Student) are the same object.
Student related attributes
Id (student number), name (name), age (age)
If the student number and name of two students are the same, it is The same object
must first modify the equals method and then compare.

Five, abstract classes and interfaces

1. The background of abstract methods

"Use advancement and abolition retreat": In the field of polymorphism, instance methods in the parent class that are overridden by subclasses have gradually faded in function, and simply removed the method body and degenerated into an abstract method.

2. Rules for using abstract methods

1. Abstract methods have no method body

2. The class containing abstract methods must be abstract

3. There can be no abstract methods in abstract classes for the time being

4. What is the relationship between abstract methods in abstract classes and subclasses?

(1) If the subclass fully implements the abstract method of the parent class, then the subclass does not need to be declared as an abstract class

(2) If the subclass does not fully implement the abstract method of the parent class, then the subclass must be declared as an abstract class

3. Syntax rules for abstract classes:

1. The class modified by abstract is an abstract class

2. There can be abstract methods in an abstract class, that is, methods modified by abstract, or none.

3. Abstract methods have no method body, only method declarations.

4. Subclasses inheriting abstract classes need to rewrite all the abstract methods of the parent class, otherwise, the subclass must also be declared as an abstract class

5. The abstract class has a construction method, but it cannot be called explicitly, that is, it cannot be instantiated, or the abstract class has no objects. -Prevent direct calling of abstract methods

6. The construction method of the abstract class is only implicitly called when the subclass is instantiated.

7. The use of abstract classes is generally as a reference type, pointing to non-abstract reference instances, reflecting polymorphism.

8. Neither the construction method nor the static method can be abstractly decorated.
Static methods cannot be overwritten (overridden) by subclasses. Once declared as an abstract method, there will never be a concrete implementation.

4. Interface:

Define an interface:
public interface interface name { }

Interface members:
member attributes: public static final (public static constant) type
member method: public abstract (public abstract method) or static method

Application understanding of the
interface : An interface can be understood as a defined set of general-purpose components, or a functional module that provides services to the outside world, with specific features that are replaceable and detachable. Interfaces are more abstract than abstract classes, and have been completely abstracted to nowhere.

The interface is usually used as the member attribute of the entity class, and the entity class is an affiliation, not a containment relationship.
Why are the properties in the interface static constants?

(1) First, the interface cannot be instantiated because it lacks the implementation of methods. This is consistent with the abstract class.

(2) Since it cannot be instantiated, the member variable can only be static

(3) Because it is static, all classes that implement the interface share a copy

(4) Since everyone shares a copy, the definition of an interface is "all people who implement the interface share these attributes/functions"

(5) Since all implementation classes are jointly owned, if it is a variable, a change in the implementation class A will result in a change in the implementation B

(6) Things that will change due to the operation of the implementation class violate the definition of the interface

(7) So in order to ensure that each implemented interface complies with this "attribute", the attribute must be final

(8) Since the definition of the interface itself is public, the last is public static final xxx

(9) If the above description is not clear enough, it should be understood as: Turtle's buttocks-turtle bulge

5. About default:

1. Starting from Jdk8, instance methods are allowed in the interface, but they must be modified by default

2. Background:
For an existing interface, if you want to add a new method to the interface, you need to modify all the classes that implement the interface. If the interface has a lot of existing classes, it will bring a lot of work. And it's easy to break the previous code and cause some problems. If you define the new method as the default method, you can avoid the modification of other implementation classes.

3. Syntax rules :
1. The implementation class does not need to override the default modification method but will also inherit the default method in the interface

2. If a class implements interfaces A and B at the same time, and interfaces A and B have the same default method, at this time, the class must override the default method in the interface. Why should it be rewritten? The reason is that when a class inherits the default method in an interface, it does not know which interface's default method should be inherited.

3. If the subclass inherits the parent class, the parent class has the b method, and the interface implemented by the subclass also has the b method (modified by default), then the subclass needs to rewrite the b method in the parent class and the interface at the same time.

4. If an interface A is marked as a functional interface, then the abstract method in the parent interface it inherits must be rewritten with the default method, because the requirement of a functional interface is that there can only be one abstract method in an interface. The sum of the abstract methods in interface A plus the number of abstract methods in the inherited parent interface can only be 1.

6. Summary

1. Abstraction: Interface>Abstract Class>Class>Object

2. The abstract class cannot explicitly call the constructor, and cannot directly create the object, but it can be implicitly called when the subclass calls the constructor.

3. There are only abstract methods and static methods in the interface, the default method, and no construction method.

4. Interface: Provides a port for connecting external components, understood as a socket, slot. So properties and methods must be public

5. Abstract classes remove the concept of objects, and interfaces further remove the concept of classes.

6. The properties in the interface do not have set/get, that is, they cannot be encapsulated. They are static final types, because the interface can no longer be understood as a class, but a component. The attributes of the components have been finalized when they leave the factory.

7. The evolution of the use of polymorphism:

  1. Fu f=new Zi(); Fu is an ordinary class
    2.Fu f=new Zi(); Fu is an abstract class
    3.Fu f=new Zi(); Fu is an interface, (most used)

Guess you like

Origin blog.csdn.net/StruggleBamboo/article/details/111389710