Basic Java Knowledge
Java is a high-level Internet-facing programming language introduced by Sun (Stanford University Network, Stanford University web Company) in 1995.
Java VM (Jvm:java virtual machine)
JRE (Java Runtime Environment): Java Runtime Environment
(including the core class libraries required by the JVM and Java programs, etc., to the user)
JDK (Java Development Kit) Java Development Kit (including JRE, for Java Developers)
Set temporary environment variables using set
java set Path=xxx
When writing a simple HelloWorld program, you can make the Java file name inconsistent with the class name, the resulting bytecode file name is the same as the class name , and when the class containing the main function has public, you must make the Java file name and class name consistent, the specified .
Note the difference set Classpath=c: With Set classpath=c:; The difference (semicolon has no), no semicolon only in the current directory to find, add a semicolon first to the current directory to find. So don't add the semicolon as well later.
Note the difference between the path and the Classpath lookup:
Path is the first to the current directory lookup, not found, and then to the path environment to find;
Classpath is first to CLASSPATH environment lookup, not found, and then to the current directory lookup (the premise plus a semicolon)
Documentation: For document annotations, Java-specific annotations, where the notes can be parsed by the tool Javadoc.exe provided by the JDK, generating a set of documentation for the program as a Web file
Configuring the JAVA development environment
JAVA_HOME = D:\jdk1.8.0_144PATH = .;%PATH%;%JAVA_HOME%\bin;%JAVA_HOME%\jre\bin;CLASSPATH = .;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar
JAVA Environment Installation Verification
java -versionjavac -version
The first JAVA program
publicclass Demo{ publicstaticvoidmain(String[] args) { System.out.println("Hello Java!"); }}
Identifier
The composition of identifiers: numbers, letters, underscores, dollar signs
Numbers cannot be used at the beginning.
You can use Chinese as the variable name (the text of the edit code should be in GBK format to support Chinese as the variable name)
Specification for names in Java
Package Name: All letters are lowercase when multiple words are composed (xxxyyyzzz)
Class name Interface name: When multiple words are composed, the first letter of all words is capitalized (xxxyyyzzz)
Variable name and function name: When multiple words are composed, the first letter is lowercase, the second word starts with the first letter of each word (xxxyyyzzz)
Constant name: All letters are capitalized, and when multiple words are underlined, each word is connected with an underscore (xxx_yyy_zzz)
Constants and variable constants
- Constants can be defined in Java with the final keyword. For example: final int i = 0;
Data type
Data type = base data type + reference data type
Basic Data type = Integer (byte,short,int,long) + floating-point (float,double) + char (char) + Boolean (Boolean)
Reference data type = class + interface (interface) + array ([])
1, Integer type
BYTE (-128 ~ 127)
Short (-32768 ~ 32767)
Int (-2147483648 ~ 2147483647)
Tips:
- There are no unsigned integer variables in JAVA
- Implicit type conversion (byte,short,char->int->long->float->double)
- Byte,short,char do not convert to each other, they are first converted to an int type when calculating, and then calculated.
- When a large-capacity data type is converted to a small-capacity data type, it is necessary to strengthen the conversion character, but it can result in reduced precision or overflow.
- When there are multiple types of data blending operations, the system first automatically converts all data to the one that has the largest capacity and then calculates it.
2, floating-point type
- Float floating-point number in JAVA plus suffix f or f.
- Double floating-point numbers in JAVA plus the suffix D or D.
- The default type of JAVA floating-point number is double.
- Casting a number of type float to a long type will shed the fractional part instead of rounding it.
3. Logic type and character type
- The logical type in Java, also known as Boolean, is a type that can only represent true and false two values.
- The character type in Java occupies two bytes and can represent Unicode characters (such as kanji).
char c1 = ‘c‘;char c2 = ‘冯‘;
4. Reference data type
- The reference data type in JAVA is similar to the pointer type in C language;
- Reference data types in JAVA are primarily used for complex data types defined by class classes (not basic data types, which are not highlighted in code, such as String types, which are complex data types defined by class. )
- Reference data type variables and constants in JAVA are defined in the same way as basic data types.
- Reference data types include: Class classes, interface interface, arrays.
Operator
1. Arithmetic operators
- + + and--highest priority
- Multiply,/,% priority second
- + and-Lowest priority
- Parentheses can change precedence
Tips:
1, if the negative number modulo, you can ignore the negative number of the modulus, such as 5%-2=1, but the modulus is a negative number is another matter.
2, for Division sign "/", its integers in addition to decimals are divided by the difference: when the division is divided, only the whole part of the integer is retained and the fractional part is left, and the result is a floating-point type when dividing between decimals (whether the divisor is a decimal or dividend is a decimal number).
3, "+" in addition to the function of the sum of strings, but also to convert a non-string into a string. (System.out.println ("5+5=" +5+5); only one of the operands on either side of the "+" operator is a string type, and the system automatically converts the other operand to a string and then connects. )
2. Logical operators
- ! Highest Operation priority
- && Operation Priority Second
- || Lowest operation Priority
- Parentheses can change precedence
3. Relational operators
- Variables and constants of the same type in JAVA can be judged equal by using = = and! =.
- The result of the relational operator in JAVA is a Boolean value, not 1 or 0 in the C language;
- Relational operators are often used in conjunction with logical operators.
4, bitwise operators
- Bitwise operators are operators that perform binary operations on integers, and the returned result is also an integer;
- Bitwise operators have bitwise inversion ~, bitwise and &, bitwise OR | and bitwise XOR ^;
- The shift operator is left-shifted <<, right->>, unsigned right shift >>>.
5. Conditional operators
- Conditional operators in Java return a value based on the condition
- x = (Boolean expression)? (The value assigned when true): (the value assigned when false);
- For example: String s = (num < 2500)? ("No pressure on the mortgage"):("the mortgage is too high");
1, if-else-
2, switch-case-
- The conditional expression in a switch statement can only be Int,short,byte,char
- The case in a switch statement must be constant and cannot be duplicated.
Member variables
The difference between a member variable (a property of a class) and a local variable:
Member variables: if not initialized and assigned, the default initial value is 0
Local variables: When there is no initialization, there will be an error when accessing the
Reference
- Variable types other than primitive types in the JAVA language are referred to as reference types, such as String types.
When using string s; , there are actually two pieces of memory, one is an index called S (Stack), which contains an address, when s = new String ("JAVA"); , S points to another space (heap), the content of this space is "JAVA". So S is not "Java", but a reference to "Java".
Referring to the concept of a reference, immediately think of a small piece of memory (stack) pointing to a large chunk of memory (heap).
Construction method
- Create a new object using the new + construct method
- When a constructor is not specified, the compiler automatically adds a default constructor for the class.
- The constructor method is a function in the JAVA class that initializes the object.
- The constructor method has the same name as the class and no return value
Chapter Three Memory parsing 6-11 lesson is really wonderful, not much to say, own look!!!
Method Overloading (overload)
- Same method name + parameter: Different number of parameters/different parameter types
- The return value type is different (does not constitute an overload)
As with normal methods, construction methods can also be overloaded
Different types of memory distributions
When the object is created, static variables, static methods will be put into memory, even if there is no new object, static variables still exist in the data segment region.
Memory is divided into four zones:stack segment,heap segment,data segment,code segment;
The stack area holds function parameters and local variables;
The heap stores objects (including member variables: member variables are allocated in heap memory, because member variables allocate space only when new comes out, so they are allocated in heap memory, while local variables are allocated in stack memory. );
The data area holds static variables or string constants;
The method of storing class in code area;
This pointer
- The This keyword used in the method definition of a class represents a reference to an object that uses the method.
- Which object calls the method's This,this points to which object.
- This can be seen as a member variable whose value is a reference to the current object.
Static keyword
- In a class, the member variable declared with static is a static member variable, which is the function variable of the class, initialized at the first use (when new object is first used), and only one copy of the static member variable for all objects of that class.
- The method declared with static is a static method, and when the method is called, the object's reference is not passed to it, so the non-static member is not allowed in the static method.
- The static member variable is allocated in the data area, so the layout of the memory, in addition to the stack and heap, a piece of data Segment area.
Static member variables can be accessed using the "class name. Static member variable", which can also be accessed using the object. Static member variable.
Static member functions cannot call non-static member and non-static member functions because static member functions do not require a new object to come out (a static method that uses the static declaration method, and the object's reference is not passed to it when the method is called). Therefore, the static member function cannot invoke non-static member variables and non-static member functions, since there is no object in the static method, and non-static member variables and non-static member functions cannot be executed.
Both static and non-static member variables can be assigned at the time of definition, but with different meanings.
Package and Import
To facilitate the management of numerous classes in large software systems, solve the problem of naming conflicts of classes, the Java ingestion Package mechanism, which provides multiple class namespaces for classes. The equivalent of a different class of the same name with a unique path.
The package statement, as the first statement in the Java source file, indicates the packages for the classes defined in the file. (If the default package statement is a nameless package)
To the package name, the conventional is the company's domain name upside down: For example, the company for www.google.com, then to your class packaging when the name can be: Package com.google.javatest;
The Java compiler applies the package to the directory management of the file system, in the packages statement, with "." To indicate the hierarchy of the package directory, such as the Com.google.javatest, which indicates that the class in the file is located under the "./com/google/javatest" directory. If the class of the file is called by another class, the class file for that file needs to be located in the "./com/google/javatest" directory.
If one of the classes in the file is called a cat class, then when used in other classes, such as new, a Cat object, then write this:
java com.google.javatest.Cat cat = new com.google.javatest.Cat();
* * The Cat class path needs to be added, otherwise the cat class cannot be found (if a class is packaged, the class's full name must be used if the class is used, and the Java compiler can find the Class). This is too much trouble, the solution is to use import. Use import to introduce the class you want to use at the beginning of the file, such as import Com.google.javatest.cat;import com.google.javatest.*;**
you do not need to use the import statement to directly use the classes in the Java.lang package, such as the String class .
Note that the packaged source files may have an impact on compilation, and you can delete or transfer directories from the source files (Java source files) that finished the package (which generated the corresponding class file).
Note: If you follow the above import Com.google.javatest.Cat, then we call the Cat class Java source file path to the same directory as the COM path, otherwise the path will not be found. (The parent directory of the top-level package for the class file must be located under Classpath.) For example, the top-level package for the class file above is the COM directory, the parent directory of the COM directory is the current directory, or "." Directory, which is located in the Classpath directory. )
Java-Provided packages
How do you see what packages are available in Java? Located inside the D:\Java\jdk\jre\lib\rt.jar, extracted can be seen.
Main Package Description:
- Java.lang contains some of the core classes of the Java language, such as String,math,integer,system and thread, that provide common functionality.
- java.awt contains several classes that make up the toolset of the abstract window, which are used to build and manage the graphical user interface (GUI) of the application.
- The java.applet contains some of the classes required for the applet to run.
- The java.net contains classes that perform network-related operations.
- The java.io contains classes that can provide multiple input and output functions.
- Java.util contains a number of utility classes, such as sing, a system feature that is useful for functions related to date calendars.
PS: You may not need to use the import statement to directly use the Java.lang package.
How do we pack our own packages as jar files? Execution: JAR-CVF xxx.jar Path (path indicates the route of the package you need to package)
You can set the jar package file as a path to the CLASSPATH variable so that we can use the jar package. The effect is the same as the real path.
Inheritance and Permissions control
modifier |
class Internal |
Same Package |
subclass (can be different packages) |
non-subclasses of different packages |
Private |
Yes |
|
|
|
Default |
Yes |
Yes |
|
|
Protected |
Yes |
Yes |
Yes |
|
Public |
Yes |
Yes |
Yes |
Yes |
- The visibility of the class
- The Java language states that only one class of a file is declared public
- The public class must be exactly the same as the file name.
- The public class can be imported using classes from other packages, and the default class is accessible only to classes within the same package
- Protected and private cannot be used to qualify the visibility of a class, only public and default are allowed for the class's adornment permission
- The inheritance mechanism of a class is implemented in Java using the extends keyword.
- Java only supports single inheritance and does not allow multiple inheritance.
- Each property and method explicitly declares access permissions and does not use the default permissions.
- For properties and methods that are not logically visible externally, try to set it to private.
- Although other non-subclasses in the same package in the Java language have free access to protected members, this is not recommended.
- Organizes logically related classes in a package, organizing the class of the program in the form of a package.
Method Overrides (Override/overwrite)
Methods that inherit from a base class can be overridden in a subclass as needed.
The overriding method must have the same method name, parameter list, and return value as the overridden method. (That's the way it's done)
The overriding method cannot use more restrictive access than the overridden method.
Super keyword
Use Super in Java to refer to the members of the base class.
When a child class and a parent class have a member variable of the same name, the subclass member variable does not overwrite the parent class member variable, the subclass member variable overrides the member variable of the parent class, causes the parent class member variable to be hidden, and super can access the parent class member variable.
-When a subclass inherits from a parent class, it is equivalent to a subclass that automatically has two more member variables, one that is this, a pointer to the subclass object, and a super pointer to the parent class object in the Subclass object.
How to construct in inheritance
The constructor of the subclass must be called during the construction of its base class (first parent, after guest, last self)
Subclasses can use super to call the constructor of the base class in their own construction method (use this to invoke another constructor of this class)
If the constructor method of a subclass does not explicitly call the constructor of the base class, the system defaults to calling the parameterless construction method of the base class.
If the subclass constructor method does not explicitly call the base class construction method, and there is no parameterless constructor in the base class, the compilation error occurs.
The ToString method of the Object class
The object class is the root class for all Java classes.
If the extends keyword is not used in the declaration of a class to indicate its base class, the default base class is the object class.
The ToString method of the Object class, it is recommended to overwrite this method for all subclasses (It is recommended, so all subclasses override the this approach.)
The Equals method of the object class
The object class defines the public Boolean equals (Object obj) method, which provides the logic for whether an object is equal.
The Equals method of object is defined as: X.equals (y) returns True when X and Y are references to the same object, otherwise false.
Some classes provided by the Java SDK, such as String,date, override the Equals method of object, call the Equals method of these classes, X.equals (y) when the objects referenced by x and Y are the same class object and the property is the same (not necessarily the same object), return True, otherwise false is returned.
You can override the Equals method as needed.
Object transformation
A reference-type variable of a base class can point to an object of its child class.
A reference to a base class does not have access to the newly added members (properties and methods) of its child class objects.
You can use (reference variable instanceof class name) to determine whether the object that the reference variable points to belongs to the class or subclass of the class.
The object of a subclass can be used as an object of the base class as an upward transformation and vice versa.
polymorphic/Dynamic binding/Late binding
- To have inheritance
- Subclasses overriding parent class methods
- Parent class reference to child class object
- When the parent class refers to a child class object, the parent object cannot access the new member variables and member methods of the child class.
Abstract class
When you decorate a class with the abstract keyword, this class is called an abstract class, and when you use abstract to modify a method, the method is called an abstract method.
Classes containing abstract methods must be declared as abstract classes, abstract classes must be inherited, and abstract methods must be overridden.
Abstract classes cannot be instantiated.
Abstract methods need to be declared without implementation.
Final keyword
The value of the final variable (member variable, local variable) cannot be changed.
The final method cannot be overridden.
The final class cannot be inherited.
Interface interface
An interface is a collection of definitions of abstract methods and constant values.
In essence, an interface is a special abstract class that contains only constants (member variables of the static final type) and methods, without the implementation of variables and methods.
Interface Implementation method:
interface Singer { publicvoidsing(); publicvoidsleep();}classimplements// 学生不是继承(extends)Singer,而是实现(implements)Singer }
- Multiple unrelated classes can implement (implements similar inheritance) the same interface.
interface Singer { publicvoidsing(); publicvoidsleep();}classimplements Singer { // ...}classimplements Singer { // ...}
- A class can implement (implements similar inheritance) multiple unrelated interfaces.
classimplements Singer, Painter {}
- Like inheritance, there is polymorphism between the interface and the implementation class.
Interface Features
Interfaces can be implemented in multiple implementations.
The member variable in the interface defaults to public static final, or only public static final.
Only abstract methods can be defined in an interface, and these member methods are public by default and only public.
Interfaces can inherit other interfaces and add new properties and abstract methods.
What if two interfaces have the same method, but a class implements both interfaces at the same time?
- It just needs to be implemented once. *
If two interfaces have a method with the same name, but the return value is not the same, but what happens when a class implements both interfaces?
You say that both methods are good, but these two methods do not constitute an overload, can not distinguish between the two methods, so there is no solution, remember not to implement this. Haha, later found out again. *
- When a subclass overrides a method of a parent class, access to the method must be equal to or greater than the method access permission of the parent class, that is, the permissions of the method that implements the interface must be public, because the method of the interface is public.
Otherwise, the compilation error is:
"' Java
TEST.JAVA:44: Error: Playwithpet () in worker cannot implement Playwithpet () in Petcarer
void Playwithpet () {
^
Attempting to assign lower access rights; Formerly public *
```
01-java Foundation and object-oriented